
Simplify Path
Problem
简化路径
Solution
用了两个 stack 来解决
其实可以用 Deque
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
public class { public String simplifyPath(String path) { String[] strs = path.split("/"); Stack<String> stack = new Stack<>(); String back = ".."; String cur = "."; for(String str : strs) { if(str.equals(back)){ if(!stack.isEmpty()) { stack.pop(); } continue; } if(str.equals(cur) || str.equals("")){ continue; } stack.push(str); } if(stack.isEmpty()){ return "/"; } else { Stack<String> stack1 = new Stack<>(); while(!stack.isEmpty()){ stack1.push(stack.pop()); } stack = stack1; StringBuilder sb = new StringBuilder("/"); while(!stack.isEmpty()){ sb.append(stack.pop()); sb.append("/"); } sb.deleteCharAt(sb.length()-1); return sb.toString(); } } }
|
Over!
近期评论