题意:编写一个基本的计算器,实现加减法操作。
思路:用堆栈完成优先级操作。
class Solution {
public:
int calculate(string s) {
stack<char> cal;
for(int i = 0; i < s.length(); ++ i) {
if(s[i] == ' ') continue;
if(s[i] ==')') {
string temp;
while(cal.top() != '(') {
temp +=cal.top();
cal.pop();
}
cal.pop();
std::reverse(temp.begin(), temp.end());
// cout << temp << endl;
temp = re(temp);
//cout << temp << endl;
for(int i = 0; i < temp.length(); ++ i) cal.push(temp[i]);
}
else cal.push(s[i]);
}
string c;
while(!cal.empty()) {
if(cal.top() == '(' || cal.top() == ')') continue;
c += cal.top();
cal.pop();
}
//cout << c << endl;
std::reverse(c.begin(), c.end());
if(c[0] == '+') return std::stoi(c.substr(1));
if(c[0] == '-') return -std::stoi(c.substr(1));
c = re(c);
return std::stoi(c);
}
string re(string s) {
vector<string> nums;
vector<char> op;
string temp;
for(int i = 0; i < s.length()- 1; ++ i) {
if(s[i] == '+' && (s[i + 1] == '-' || s[i + 1] == '+')) s[i] = ' ';
if(s[i] == '-' && s[i + 1] == '+') s[i + 1] = ' ';
if(s[i] == '-' && s[i + 1] == '-') {
s[i] = ' ';
s[i + 1] = '+';
}
}
for(int i = 0; i < s.length(); ++ i) {
if(s[i] == ' ') continue;
if(s[i] == '+' || s[i] == '-') {
op.push_back(s[i]);
nums.push_back(temp);
temp = "";
}
else temp += s[i];
}
if(temp.length()) nums.push_back(temp);
if(op.size() == 0) return s;
if(nums.size() - op.size() != 1) return s;
int sum = std::stoi(nums[0]);
for(int i = 0; i < op.size(); ++ i) {
if(op[i] == '+') sum += std::stoi(nums[i + 1]);
if(op[i] == '-') sum -= std::stoi(nums[i + 1]);
}
return to_string(sum);
}
};