题目来源
题目描述
题目解析
这道题和leetcode:150. 后缀表达式求和几乎是一模一样的。考察的是字符串切割以及逆波兰表达式
#include <utility>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class Solution{
std::string calOne(std::stack<std::string> &stack){
if(stack.size() < 3){
return "error";
}
auto second = stoi(stack.top()); stack.pop();
auto first = stoi(stack.top()); stack.pop();
auto sign = stack.top(); stack.pop();
int res = 0;
if(sign == "add"){
res = first + second;
}else if(sign == "sub"){
res = first - second;
}else if(sign == "mul"){
res = first * second;
}else{
if(second == 0){
return "error";
}
res = first / second;
}
return to_string(res);
}
public:
std::string solve(std::string str){
// 题目涉及数字均为整数,可能为负;
std::stack<std::string> stack;
int i = 0;
while (i < str.size()){
if(str[i] == '('){ // 遇见了起始
stack.push( str.substr(i + 1, 3));
i += 4;
}else if((str[i] >= '0' && str[i] <= '9') || str[i] == '-'){
int j = i; // 找下一个' '或者')'
while (j < str.size() && str[j] != ' ' && str[j] != ')'){
j++;
}
stack.push(str.substr(i, j - i));
i = j;
}else if(str[i] == ' '){
i++;
}else{
auto ans = calOne(stack);
if(ans == "error"){
return "error";
}
stack.push(ans);
i++;
}
}
return stack.empty() ? "0" : stack.top();
}
};
int main(){
Solution a;
std::cout << a.solve("(mul 3 -7)") << "\n";
std::cout << a.solve("(add 1 2)") << "\n";
std::cout << a.solve("(sub (mul 2 4) (div 9 3))") << "\n";
std::cout << a.solve("(div 1 0)") << "\n";
}