71. Simplify Path - jiejackyzhang/leetcode-note GitHub Wiki
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
- Did you consider the case where path = "/../"? In this case, you should return "/".
- Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo".
解题思路为stack。
将有效的地址压入stack,若遇到'..'并且stack不为空,则stack.pop()。 最后将简化后的地址以"/"+dir的形式输出。
public class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
Set<String> skip = new HashSet<>(Arrays.asList("", ".", ".."));
for(String str : path.split("/")) {
if(str.equals("..") && !stack.isEmpty()) {
stack.pop();
} else if(!skip.contains(str)) {
stack.push(str);
}
}
String res = stack.isEmpty() ? "/" : "";
for(String s : stack) {
res = res + "/" + s;
}
return res;
}
}