Given an absolute path for a file (Unix-style), simplify it.
Example
"/home/"
, => "/home"
"/a/./b/../../c/"
, => "/c"
最后拼接成新路径。注意split在匹配时会出现空字符串匹配。
public class Solution {
/**
* @param path the original path
* @return the simplified path
*/
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
String[] str = path.split("/");
//考虑/...
for(int i = 0; i < str.length; i++) {
if(str[i].equals(".")){
} else if(str[i].equals("..")) {
stack.pop();
} else {
stack.add(str[i]);
}
}
if(stack.isEmpty()) return "/";
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()) {
if(stack.peek().equals("")) stack.pop();
else sb.insert(0, "/" + stack.pop());
}
return sb.length() == 0 ? "/" : sb.toString();
}
}