Description
https://leetcode.com/problems/simplify-path/
给定一个Unix风格的绝对路径,简化之
Solving Ideas
栈的应用
- 遇到
./
,忽略 - 遇到
../
,出栈 - 遇到文件名(如
.a
,b
,abc
等等,其中以.
为开头的为隐藏文件),入栈
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
Solution
class Solution {
public String simplifyPath(String path) {
LinkedList<String> stack = new LinkedList<>();
int i = 0;
while (i < path.length()) {
while (i < path.length() && path.charAt(i) == '/') i++;
StringBuilder sb = new StringBuilder();
while (i < path.length() && path.charAt(i) != '/') sb.append(path.charAt(i++));
String tmp = sb.toString();
if (tmp.equals("..")) {
if (!stack.isEmpty()) stack.removeLast();
} else if (!tmp.equals("") && !tmp.equals(".")) {
stack.addLast(tmp);
}
}
return "/" + String.join("/", new ArrayList<>(stack));
}
}