文章目录
1. 题目
2. 思路
(1) 栈+双指针法
- 遍历路径,利用栈和双指针法模拟即可。
3. 代码
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public String simplifyPath(String path) {
int n = path.length();
LinkedList<String> list = new LinkedList<>();
int left = 0;
int right = 0;
while (left < n) {
while (left < n && path.charAt(left) == '/') {
left++;
}
if (left < n) {
right = left;
while (right < n && path.charAt(right) != '/') {
right++;
}
String s = path.substring(left, right);
if (s.equals("..")) {
if (list.size() > 0) {
list.pollLast();
}
} else if (!s.equals(".")) {
list.offerLast(s);
}
left = right;
}
}
if (list.isEmpty()) {
return "/";
}
StringBuilder sb = new StringBuilder();
while (!list.isEmpty()) {
sb.append('/');
sb.append(list.pollFirst());
}
return sb.toString();
}
}