- 此题主要考察的是栈,所以定义一个辅助栈;
- 先把字符串以"/“为分隔符分割成数组,此时数组有 [“路径”],[”"],["."],["…"]这四种情况;
- 遍历数组,当s[i].equals("…")并且栈不空时pop,当!s[i].equals("") && !s[i].equals(".") &&!s[i].equals("…"),即s[i]是路径入栈;
- 栈空,返回"/",栈非空,用StringBuffer做一个连接返回即可;
- 结束
public String simplifyPath(String path) {
Stack<String> result = new Stack<>();
for (String str : path.split("/")) {
if (str.equals("..")) {
int i = 0;
while (!result.empty() && i < 2) {
result.pop();
i++;
}
} else if (str.equals("")) {
continue;
} else if (str.equals(".")) {
continue;
} else {
result.push("/");
result.push(str);
}
}
if (result.size() == 0)
result.push("/");
StringBuilder sb = new StringBuilder();
while (!result.empty()) {
String obj = result.firstElement();
sb.append(obj);
result.removeElement(obj);
}
return sb.toString();
}