Q:
Given a string s
which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]
.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
.
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.
A:
走3遍, 第一遍, 都分割, 成为list 形式的string
第二遍。 做 / * 运算
第三遍, 做 + - 运算
class Solution { public: int calculate(string s) { // first convert s to list of symbols vector<string> V; int start = 0; while(start < s.length()){ if(s[start]==' '){ start++; }else if(s[start]=='/' || s[start]=='+' || s[start]=='-' || s[start]=='*'){ V.push_back(s.substr(start,1)); start++; }else{ int end = start+1; while(end < s.length() && isdigit(s[end])){ end++; } V.push_back(s.substr(start,end-start)); //substr (expect the 2nd as length) start = end; } } vector<string> V2; // calcualte / * first for(int i =0; i<V.size(); ++i){ if(V[i] == "*" || V[i] == "/" ){ int tmp = 0; if(V[i] == "*"){ tmp = stoi(V2.back()) * stoi( V[i+1]); }else{ tmp = stoi(V2.back()) / stoi( V[i+1]); } V2.pop_back(); ++i; V2.push_back(to_string(tmp)); }else{ V2.push_back(V[i]); } } for(int i =0; i<V2.size(); ++i){ cout << i<< ":" << V2[i] <<endl; } int res = stoi(V2[0]); // calcualte + - for(int i =1; i<V2.size(); ++i){ if(V2[i] == "+" || V2[i] == "-" ){ if (V2[i] == "+" ){ res += stoi(V2[i+1]); }else{ res -= stoi(V2[i+1]); } ++i; } } return res; } };
No comments:
Post a Comment