题目
Given an absolute path for a file (Unix-style), simplify it.
For example
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
答案
粗暴解题法,自己分割string,调试很久才成功
class Solution {
public String simplifyPath(String path) {
if(path.equals("")) return "";
Stack<String> stk = new Stack<String>();
int left = 1, right = path.length() - 1, slash = 0;
while(left <= right) {
String token;
int slash2 = path.indexOf('/', left);
if(slash2 != -1) {
token = path.substring(slash + 1, slash2);
slash = slash2;
left = slash2 + 1;
}
else {
token = path.substring(slash + 1);
left = right + 1;
}
if(!token.equals("") && !token.equals(".")) {
if(token.equals("..")) {
if(!stk.isEmpty())
stk.pop();
}
else {
stk.push(token);
}
}
}
StringBuilder sb = new StringBuilder();
if(stk.isEmpty()) return "/";
while(!stk.isEmpty()) {
sb.insert(0, "/" + stk.pop());
}
return sb.toString();
}
}
用split函数
class Solution {
public String simplifyPath(String path) {
Stack<String> stk = new Stack<String>();
for(String token : path.split('/')) {
if(token.equals("") || token.equals(".")) continue;
if(token.equals(".."))
if(!stk.isEmpty()) stk.pop();
else
stk.push(token);
}
StringBuilder sb = new StringBuilder();
while(!stk.isEmpty()) {
sb.insert(0, "/" + stk.pop());
}
return sb.isEmpty()? "/" : sb.toString();
}
}