• <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;
        }
    }
  • 相关阅读:
    穷举 迭代 while
    for 循环
    switch case
    if else 语句
    数据类型
    语句的输入、输出
    控件——DataGridview
    mysql-bin.000001文件的来源及处理方法
    /var/log目录下的20个Linux日志文件功能详解
    CountDownLatch
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11939049.html
Copyright © 2020-2023  润新知