150. Evaluate Reverse Polish Notation
class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<Integer>(); for(int i = 0; i < tokens.length; i++){ switch(tokens[i]){ case "+": stack.push(stack.pop() + stack.pop()); break; case "-": stack.push(-stack.pop() + stack.pop()); break; case "*": stack.push(stack.pop() * stack.pop()); break; case "/": int n1 = stack.pop(), n2 = stack.pop(); stack.push(n2 / n1); break; default: stack.push(Integer.parseInt(tokens[i])); } } return stack.pop(); } }
71. Simplify Path
class Solution { public String simplifyPath(String path) { if(path == null || path.length() == 0) return ""; path = path.trim(); Stack<String> stack = new Stack<>(); String[] s = path.split("/"); for(int i = 0; i < s.length; i++){ //.. if(!stack.isEmpty() && s[i].equals("..")){ stack.pop(); }else if(!s[i].equals(".") && !s[i].equals("..") && !s[i].equals("")){//.,..,空白以外的 stack.push(s[i]); } } //组装 List<String> list = new ArrayList<>(stack); return "/" + String.join("/", list); } }
388. Longest Absolute File Path
最后len -1是减去末尾不需要的 / 的长度。
class Solution { public int lengthLongestPath(String input) { Deque<Integer> stack = new ArrayDeque<>(); stack.push(0); // "dummy" length int maxLen = 0; for(String s:input.split(" ")){ int lev = s.lastIndexOf(" ")+1; // number of " " while(lev+1<stack.size()) stack.pop(); // find parent int len = stack.peek()+s.length()-lev+1; // remove "/t", add"/" stack.push(len); // check if it is file if(s.contains(".")) maxLen = Math.max(maxLen, len-1); } return maxLen; } }