zoukankan      html  css  js  c++  java
  • <Stack> 150 71 388

    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;
        }
    }
  • 相关阅读:
    loadrunner提高篇
    loadrunner提高篇
    loadrunner提高篇
    STM32F4XX高效驱动篇1-UART
    系统封装接口层 cmsis_os
    uCGUI 按键窗口切换机制
    xming+xshell让linux变成桌面化操作
    jmeter做WebSocket请求解读
    性能监控工具spotlight操作
    linux性能监控命令,磁盘,网络,cpu,内存
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11939049.html
Copyright © 2011-2022 走看看