224. Basic Calculator


July-11-2019

这个大概没H的难度。
只有加减的话,主要的麻烦在于处理括号,然后用STACK好像是共识了。。
唯一需要注意的是括号会造成变号,因为只有加减,+-其实就是1-1的区别。
遇到(先当前sign进栈,再当前res进栈,然后res = 0当做一个新的式子重新算,直到发现)出栈。
O(n)

    public int calculate(String s) {
        if (s == null || s.length() == 0) return 0;
        
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        int res = 0;
        int sign = 1;
        
        for (int i = 0; i < s.length(); i ++) {
            char tempChar = s.charAt(i);
            if (Character.isDigit(tempChar)) {
                int tempVal = 0;
                while (i < s.length() && Character.isDigit(s.charAt(i))) {
                    tempVal = tempVal * 10 + s.charAt(i++) - '0';
                }
                if (i != s.length()) {
                    i --;
                }
                res += (tempVal * sign);
            } else if (tempChar == '-') {
                sign = -1;
            } else if (tempChar == '+') {
                sign = 1;
            } else if (tempChar == '(') {
                stack.push(res);
                stack.push(sign);
                res = 0;
                sign = 1;
            } else if (tempChar == ')') {
                res = res * stack.pop() + stack.pop();
            }
        }
        
        return res;
    }

二刷。

解决括号。

sign是括号外的符号,进入括号之后要提前变号。

SIGN有2种,一种是括号内的SIGN,就是当前同级的符号

res = res + temp * sign;

这里是类似于 -(4 - 54) 比如54的符号是-。

res = res * stk.pop() + stk.pop();

后面碰到")"的时候,此时符号是括号前的符号
-(4-54),第一个POP的就是符号,是最前面的-。

public class Solution {
    public int calculate(String s) {
        int res = 0;
        if (s.length() == 0) return res;
        
        Stack<Integer> stk = new Stack<>();
        int sign = 1;
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                int temp = 0;
                while (i < s.length() && Character.isDigit(s.charAt(i))) {
                    temp = temp * 10 + s.charAt(i) - '0';
                    i ++;
                }
                if (i < s.length()) {
                    i --;
                }
                res = res + temp * sign; 
            } else if (c == '+') {
                sign = 1;
            } else if (c == '-') {
                sign = -1;
            } else if (c == '(') {
                stk.push(res);
                stk.push(sign);
                res = 0;
                sign = 1;
            } else if (c == ')') {
                res = res * stk.pop() + stk.pop();
            }
        }

        return res;
    }
}
posted @ 2016-12-08 13:28  哇呀呀..生气啦~  阅读(191)  评论(0)    收藏  举报