Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
public class Solution {
public String simplifyPath(String path) {
if(path == null || path.length() == 0){
return null;
}
String[] array = path.split("/");
LinkedList<String> stack = new LinkedList<String>();
for(int i=0; i<array.length; i++){
if(array[i].equals("/") ||array[i].equals(".")){
continue;
}else if(array[i].equals("..")){
if(!stack.isEmpty()){ //记得加上判断条件
stack.pop();
}
}else{
if(!array[i].equals("")){ //记得加上判断条件
stack.push(array[i]);
}
}
}
StringBuilder sb = new StringBuilder();
if(stack.isEmpty()){
sb.append("/");
return sb.toString();
}
for(int i=stack.size() - 1; i>=0; i--){
sb.append("/");
sb.append(stack.get(i));
}
return sb.toString();
}
}