The expression string contains only non-negative integers, +, -, *, / operators and empty spaces. 
The integer division should truncate toward zero.

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
这题只有基本的四则运算符号,不包含括号。模拟计算器的难点在于,运算法则里符号有优先级,先乘除后加减。
人类的逻辑是先找到乘除的部分,单独计算这些部分,变成整数,和加减一起运算,代码模拟起来麻烦且费时。
按照从左到右的顺序扫描,遇到加减直接运算,不会出错。但是乘除就会有问题,要特殊处理。
这里我们把上次遇到的数字存到stack里,如果遇到乘除符合,说明上次操作不对,需要从结果里减去这个数字。
而且还可以得到乘数和除数是多少,进行乘除部分的操作。
public class Solution {
    public int calculate(String s) {
        Stack<Integer> stk = new Stack<Integer>();
        int res = 0, num = 0;
        char lastSign = '+';
        char[] cArray = s.toCharArray();
        
        for(int i=0; i < cArray.length; i++){
            char c = cArray[i];
            if(c >= '0' && c <= '9'){
                num = num*10 + c -'0';
            }
            
            if(c == '+' || c == '-' || c == '*' || c == '/' || i == cArray.length-1){
                if(lastSign == '+' || lastSign == '-'){
                    int temp = lastSign == '+' ? num : -num;
                    stk.push(temp);
                    res += temp;
                }
                if(lastSign == '*' || lastSign == '/'){
                    res -= stk.peek();
                    int temp = lastSign == '*' ? stk.pop()*num : stk.pop()/num;
                    stk.push(temp);
                    res += temp;
                }
                lastSign = c;
                num = 0;
            }
        }
        return res;
    }
}

224 Basic Calculator

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces.
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
这题只有加减和括号,优先级就是括号里的先计算,所有我们把括号里的内容当做操作的基本单位。
括号外的符号就当做整体的符号,最后和括号外的同层数字进行加减运算。
比如 (2-(2+1))
初始化sign = 1, res =0;
stk{1,2,3,4,5} 简单表示stk最右的栈顶。
遇到(, stk{0, 1}, 遇到2和-, stk{0,1,2,-1}
遇到2+1 = 3, 遇到), stk弹出res = 3*(-1) +2 = -1, stk{0,1}
再遇到), stk弹出,res = -1*1 + 0 = -1.
public class Solution {
    public int calculate(String s) {
        int sign = 1, result = 0;
        Stack<Integer> stk = new Stack<Integer>();
        char[] cArray = s.toCharArray();
        for(int i=0; i< cArray.length; i++){
            if(Character.isDigit(cArray[i])){
                int num = 0;
                while(i < cArray.length && Character.isDigit(cArray[i])){
                    num = 10*num + cArray[i] - '0';
                    i++;
                }
                i--;
                result = result + sign*num;
            } else if(cArray[i] == '+'){
                sign = 1;
            } else if(cArray[i] == '-'){
                sign = -1;
            } else if(cArray[i] == '('){
                stk.push(result);
                stk.push(sign);
                result = 0;
                sign = 1;
            } else if(cArray[i] == ')'){
                result = result*stk.pop() + stk.pop();
            }
        }
        return result;
    }
}

394 Decode String

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times.
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

这里只是把对数字的操作变成了对str的操作,去括号的逻辑一样。
public class Solution {
    public String decodeString(String s) {
        Stack<Integer> numStk = new Stack<>();
        Stack<StringBuilder> sbStk = new Stack<>();
        int num = 0;
        StringBuilder cur = new StringBuilder();
        for(char c: s.toCharArray()){
            if(c >= '0' && c <= '9'){
                num = num*10 + c -'0';
            } else if(c == '['){
                numStk.push(num);
                sbStk.push(cur);
                num = 0;
                cur = new StringBuilder();
            } else if(c == ']'){
                StringBuilder temp = cur;
                cur = sbStk.pop();
                for(int i = numStk.pop(); i > 0; i--) cur.append(temp);
            } else {
                cur.append(c);
            }
        }
        return cur.toString();
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。