本文主要是介绍227. Basic Calculator II(Leetcode每日一题-2021.03.11),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
Constraints:
- 1 <= s.length <= 3 * 10^5
- 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.
Example1
Input: s = “3+2*2”
Output: 7
Example2
Input: s = " 3/2 "
Output: 1
Example3
Input: s = " 3+5 / 2 "
Output: 5
Solution
class Solution {
public:void eval(stack<int> &num,stack<char> &op){auto b = num.top();num.pop();auto a = num.top();num.pop();auto c = op.top();op.pop();int r;if(c == '+')r= a + b;else if(c == '-')r = a-b;else if(c == '*')r = a * b;else r = a / b;num.push(r);}int calculate(string s) {stack<int> num;stack<char> op;unordered_map<char,int> prio;prio['+'] = 1;prio['-'] = 1;prio['*'] = 2;prio['/'] = 2;for(int i = 0;i<s.length();++i){auto c = s[i];if(c == ' ')continue;if(isdigit(c)){int x = 0;int j = i;while(j < s.length() && isdigit(s[j])){x = x * 10 + (s[j] - '0');++j;}i = j-1;num.push(x);}else{while(!op.empty() && prio[c] <= prio[op.top()]){eval(num,op);}op.push(c);}}while(!op.empty())eval(num,op);return num.top();}
};
这篇关于227. Basic Calculator II(Leetcode每日一题-2021.03.11)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!