Title Description
Implement a basic calculator to evaluate the value of a simple string expression.
The string expression contains only four operators and spaces: nonnegative integer, +, -, *, / and. Integer division keeps only the integer part.
Example 1:
Input: "3 + 2 * 2"
Output: 7
Example 2:
Input: "3 / 2"
Output: 1
Example 3:
Input: "3 + 5 / 2"
Output: 5
Explain:
You can assume that all the expressions given are valid.
Do not use the built-in library function eval.
Source: LeetCode
Link: https://leetcode-cn.com/problems/basic-calculator-ii
Copyright belongs to the network. For commercial reprint, please contact the official authorization. For non-commercial reprint, please indicate the source.
Solving problems
First convert infix expression to suffix expression, and then evaluate suffix expression. Code runs extremely slowly...
class Solution { public: int calculate(string s) { string ss = ""; for(int i=0;i<s.length();i++){ if(s[i] != ' ') ss+=s[i]; } vector<string> vect; stack<int> ans; stack<string> sk; string decline = "+-/*"; map<string,int> mp = {{"+",0},{"-",0},{"*",1},{"/",1}}; string::size_type st1,st2; st1 = ss.find_first_not_of(decline); while(st1 != string::npos){ st2 = ss.find_first_of(decline,st1); if(st2 == string::npos) st2 = ss.length(); string num = ss.substr(st1,st2-st1); vect.push_back(num); st1 = ss.find_first_not_of(decline,st2); if(st1 != string::npos){ string op = ss.substr(st2,st1-st2); while(!sk.empty() && mp[sk.top()] >= mp[op]){ vect.push_back(sk.top()); sk.pop(); } sk.push(op); } } while(!sk.empty()){ vect.push_back(sk.top()); sk.pop(); } int num1,num2; for(auto it : vect){ if(it == "+"){ num2 = ans.top(); ans.pop(); num1 = ans.top(); ans.pop(); ans.push(num1+num2); } else if(it == "-"){ num2 = ans.top(); ans.pop(); num1 = ans.top(); ans.pop(); ans.push(num1-num2); } else if(it == "*"){ num2 = ans.top(); ans.pop(); num1 = ans.top(); ans.pop(); ans.push(num1*num2); } else if(it == "/"){ num2 = ans.top(); ans.pop(); num1 = ans.top(); ans.pop(); ans.push(num1/num2); } else ans.push(atoi(it.c_str())); } return ans.top(); } };