For example,
path =
"/home/"
, => "/home"
path =
"/a/./b/../../c/"
, => "/c"
public class Solution {
public String simplifyPath(String path) {
// Start typing your Java solution below
// DO NOT write main() function
Stack<String> stk = new Stack<String>();
String tks[] = path.split("\\/");
for(int i=0;i<tks.length;i++) {
String tk = tks[i];
if(tk.isEmpty() || tk.equals(".")) {
continue;
} else if(tk.equals("..")) {
if(!stk.isEmpty()) {
stk.pop();
}
} else {
stk.push(tk);
}
}
if(stk.size()==0) {
return "/";
}
String sp = "";
while(stk.size()!=0) {
sp = "/" + stk.pop() + sp;
}
return sp;
}
}
没有评论:
发表评论