leetcode 227. Basic Calculator II

1. Topic

  • 1 <= s.length <= 3 * 105
  • s is composed of integers and operators ('+','-','*','/'), separated by some spaces
  • s represents a valid expression
  • All integers in the expression are non-negative integers and are in the range [0, 231-1]
  • The question data guarantees that the answer is a 32-bit integer

Input: s = "3+2*2"
Output: 7

Two, the code

class Solution {
    
    
public:
    bool isdigit(char ch){
    
    
        return ch>='0'&&ch<='9';
    }

    int calculate(string s) {
    
    
        int len=s.length(),num=0;
        vector<int> stk;
        char ch,prevSign='+';
        for(int i=0;i<len;++i){
    
    
            ch=s[i];
            if(isdigit(ch)){
    
    
                num=num*10+(ch-'0');
            }
            if(ch!=' '&&!isdigit(ch)||i==len-1){
    
    
                switch(prevSign){
    
    
                    case '+': stk.push_back(num);break;
                    case '-': stk.push_back(-num);break;
                    case '*': stk.back()*=num; break;
                    case '/': stk.back()/=num; break;
                }
                prevSign=ch;
                num=0;
            }
            
        }
        return accumulate(stk.begin(),stk.end(),0);
    }
};

Problem-solving ideas:

  1. I used the dual stack at the beginning, but found that it took too long. Later, I discovered that the dual stack is only needed for calculators with parentheses.
  2. For calculators without parentheses, just use the number stack. It is necessary to save a previous symbol prevSign, at the beginning prevSign='+', after each new operator is read/to the end of the string, if prevSign is addition and subtraction, the number num is pushed into the stack according to the sign; if it is multiplication and division, then Multiply and divide the top element and num directly.
  3. Finally, the elements in the stack can be added. The stack here uses a vector, and an accumulate(vector.begin(),vector.end(),0) can be used to add all the elements of the vector.

Guess you like

Origin blog.csdn.net/livingsu/article/details/114657491