题目来源
题目描述
题目解析
class Solution {
struct Info{
int idx; //当前计算到的字符串
long eval; // 计算得到的值
Info(int idx, long eval) : idx(idx), eval(eval){
}
};
void pushDeque(std::deque<std::string> &deque, long num){
while (!deque.empty()){
if(deque.back() == "+" || deque.back() == "-"){
break;
}else{
std::string sign = deque.back(); deque.pop_back();
long cur = stoi(deque.back()); deque.pop_back();
num = sign == "*" ? (cur * num) : (cur / num);
}
}
deque.push_back(std::to_string(num));
}
int calDeque(std::deque<std::string> &deque){
long ans = 0;
bool add = true;
while (!deque.empty()){
auto str = deque.front(); deque.pop_front();
if(str == "+"){
add = true;
}else if(str == "-"){
add = false;
}else{
ans = add ? ans + stol(str) : ans - stol(str);
}
}
return ans;
}
// 计算idx....之后的值
// 遇到 )或者结束时停止
Info *process(string s, int i){
int N = s.size();
long curr = 0;
std::deque<std::string> deque;
while (i < N && s[i] != ')'){
if(s[i] >= '0' && s[i] <= '9'){
curr = curr * 10 + s[i] - '0';
i++;
}else if(s[i] == ' '){
i++;
}else if(s[i] == '('){ // 2 + (3 + 5) * 6 --- curr = 0
auto info = process(s, i + 1); // !!!!
curr = info->eval;
i = info->idx + 1;
}else{
pushDeque(deque, curr);
deque.emplace_back(1, s[i]);
curr = 0; // !!!!!!!!
i++;
}
}
pushDeque(deque, curr);
return new Info(i, calDeque(deque));
}
string checkStr(string &s){
int j;
for (j = s.size() - 1; j > 0 && s[j] == ' '; --j) {
}
s = s.substr(0, j + 1);
return s;
}
public:
int calculate(string s) {
s = checkStr(s);
return (int)process(s, 0)->eval;
}
};
类似题目
题目 | |
---|---|
leetcode:224. 基本计算器 Basic Calculator | |
leetcode:227. 基本计算器 II Basic Calculator II | |
772. 基本计算器 III Basic Calculator III | |
770. 基本计算器 IV Basic Calculator IV | |
150. 逆波兰表达式求值 Evaluate Reverse Polish Notation |