class Solution {
public String simplifyPath(String path) {
// 用栈保存路径
Deque<String> stack = new LinkedList<>();
for (String s : path.split("/")) {
// 返回上层
if (s.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else if (!s.equals(".") && !s.isEmpty()) {
// 新的下级目录
stack.push(s);
}
}
StringBuilder sb = new StringBuilder();
// 从栈底开始遍历
while (!stack.isEmpty()) {
sb.append("/").append(stack.removeLast());
}
if (sb.length() == 0) {
return "/";
}
return sb.toString();
}
}
class Solution {
public String simplifyPath(String path) {
StringBuilder res = new StringBuilder();
StringBuilder name = new StringBuilder();
if (path.charAt(path.length() - 1) != '/') path = path + "/";
for (int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
if (c != '/') name.append(c);
else {
String nameStr = name.toString();
if (nameStr.equals("..")) {
while (!res.isEmpty() && res.charAt(res.length() - 1) != '/') res.deleteCharAt(res.length() - 1);
if (!res.isEmpty()) res.deleteCharAt(res.length() - 1);
} else if (!nameStr.equals(".") && !nameStr.isEmpty()) {
res.append("/").append(nameStr);
}
name = new StringBuilder();
}
}
if (res.isEmpty()) return "/";
return res.toString();
}
}
标签:String,res,路径,length,isEmpty,71,path,简化,StringBuilder
From: https://www.cnblogs.com/eiffelzero/p/17973985