Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
"/../"
?"/"
."/home/foo"
.'/'
together, such as "/home//foo/"
.public class Solution { public String simplifyPath(String path) { if(path.length() == 0 || path == null) return path; String[] tokens = path.split("/"); Stack<String> stack = new Stack<String>(); for(int i = 0 ; i < tokens.length ; i++){ if(tokens[i].equals("..")){ if(!stack.isEmpty()){ stack.pop(); } else{ continue; } } else if(tokens[i].equals(".")|| tokens[i].length() == 0){ continue; } else{ stack.push(tokens[i]); } } String ret = new String(""); if(stack.isEmpty()) return "/"; Stack<String> stack2 = new Stack<String>(); while(!stack.isEmpty()){ stack2.push(stack.pop()); } while(!stack2.isEmpty()){ ret += "/"; ret += stack2.pop(); } return ret; } }