努橙刷题编

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://leetcode.com/problems/basic-calculator/

用 stack 存储当前运算符:

public class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(1); // add this for case like "1 + 1"
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                int j = i + 1;
                while (j < s.length()) {
                    if (s.charAt(j) >= '0' && s.charAt(j) <= '9') {
                        j++;
                    } else {
                        break;
                    }
                }
                int num = Integer.parseInt(s.substring(i, j));
                result += stack.pop() * num;
                i = j - 1;
            } else if (s.charAt(i) == '+' || s.charAt(i) == '(') {
                stack.push(stack.peek());
            } else if (s.charAt(i) == '-') {
                stack.push(-1 * stack.peek());
            } else if (s.charAt(i) == ')') {
                stack.pop();
            }
        }
        return result;
    }
}

也可以用 RPN 做

posted on 2017-05-26 00:42  努橙  阅读(125)  评论(0)    收藏  举报