71. Simplify Path
主要是用一个stack记录,如果碰到的是“..”,那么如果堆栈不为空,弹出堆栈里面的前一个
如果是“.”,那么什么都不做
1 public String simplifyPath1(String path) { 2 if(path == null || path.length() == 0) { 3 return ""; 4 } 5 StringBuilder sb = new StringBuilder(); 6 Stack<String> stack = new Stack<String>(); 7 int i = 0; 8 while(i < path.length()) { 9 StringBuilder temp = new StringBuilder(); 10 int index = i; 11 while(i < path.length() && path.charAt(i) != '/') { 12 temp.append(path.charAt(i)); 13 i++; 14 } 15 if(index != i) { 16 String str = temp.toString(); 17 if(str.equals("..")) { 18 if(!stack.isEmpty()) { 19 stack.pop(); 20 } 21 } else if(!str.equals(".")) { 22 stack.push(str); 23 } 24 } 25 i++; 26 } 27 int size = stack.size(); 28 for(int j = 0; j < size; j++) { 29 sb.insert(0,stack.pop()); 30 sb.insert(0,"/"); 31 } 32 return (sb.length() == 0)? "/":sb.toString(); 33 }
bug记录
第30,31行是insert,不是append,因为stack是倒序的