Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
public class Solution {
public String simplifyPath(String path) {
if (path.length() == 0) {
return path;
}
String[] split = path.split("/");
LinkedList<String> linkedList = new LinkedList<>();
for (String string : split) {
if (string.length() == 0 || string.equals(".")) {
continue;
} else if (string.equals("..")) {
if (!linkedList.isEmpty()) {
linkedList.pop();
}
} else {
linkedList.push(string);
}
}
if (linkedList.isEmpty()) {
linkedList.push("");
}
StringBuilder res = new StringBuilder();
while (!linkedList.isEmpty()) {
res.append("/" + linkedList.removeLast());
}
return res.toString();
}
}
本文介绍了一个Java方法,用于简化Unix风格文件系统的绝对路径。通过解析输入字符串并利用栈数据结构来去除多余的'.'和'..'目录,最终返回规范化的路径。
836

被折叠的 条评论
为什么被折叠?



