• <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;
        }
    }
  • 相关阅读:
    vijos1198:最佳课题选择
    vijos1071:新年趣事之打牌
    vijos1153:猫狗大战
    bzoj3594: [Scoi2014]方伯伯的玉米田
    bzoj2753: [SCOI2012]滑雪与时间胶囊
    bzoj1923: [Sdoi2010]外星千足虫
    bzoj2783: [JLOI2012]树
    bzoj4590: [Shoi2015]自动刷题机
    bzoj4580: [Usaco2016 Open]248
    bzoj4579: [Usaco2016 Open]Closing the Farm
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11939049.html
Copyright © 2020-2023  润新知