227. Basic Calculator II(重点记录上一个符号,每次判断上一个符号)

Given a string s which represents an expression, evaluate this expression and return its value

The integer division should truncate toward zero.

 

Example 1:

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

Example 2:

Input: s = " 3/2 "
Output: 1

Example 3:

Input: s = " 3+5 / 2 "
Output: 5

 

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
  • s represents a valid expression.
  • All the integers in the expression are non-negative integers in the range [0, 231 - 1].
  • The answer is guaranteed to fit in a 32-bit integer.
 
class Solution {
public:
    //带括号的话,用递归,更难一些(找到对应层级的括号并同时删除)
    int calculate(string s) {
        //利用栈: 3+5/2*3转化为 +3 +5 /2 *3
        stack<int> nums;
        int n = s.size();
        int num = 0,res =0,pre=0;
        char sign = '+';
        for(int i=0;i<n;i++){
            //if(isspace(s[i])) continue; 忽略不用管空格
            if(isdigit(s[i])){
                num = num*10+(s[i]-'0');
            }
            if(!isspace(s[i]) && !isdigit(s[i]) || i == n-1){
                switch (sign){
                case '+':
                    nums.push(num);
                    break;
                case '-':
                    nums.push(-num);
                    break;
                case '*':
                    pre=nums.top();
                    nums.pop();
                    nums.push(pre*num);
                    break;
                case '/':
                    pre=nums.top();
                    nums.pop();
                    nums.push(pre/num);
                    break;
                }
                sign = s[i];
                num = 0;
            }
            
        }
        while(!nums.empty()){
            res += nums.top();
            nums.pop();
        }
        return res;
    }
};

 

posted on 2020-12-02 20:06  wsw_seu  阅读(110)  评论(0编辑  收藏  举报

导航