Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
Solution 1: Use stack. One thing to be noticed is that, when use String split function, it may contains blank strings.path =
"/home/"
, => "/home"
path =
"/a/./b/../../c/"
, => "/c"
public class Solution {
public String simplifyPath(String path) {
String[] strs=path.split("/"); //note: may have blank string
Deque<String> stack=new LinkedList<>();
for (String x:strs) {
if (x.equals("..")) {
if (!stack.isEmpty()) stack.pop();
}
else if (x.length()>0 && !x.equals(".")) stack.push(x); //
}
StringBuilder res=new StringBuilder();
while (!stack.isEmpty()) {
res.insert(0,stack.pop());
res.insert(0,'/');
}
if (res.length()==0) return "/";
return res.toString();
}
}
没有评论:
发表评论