题面就是实现一个字符串输入的加减法计算器(带括号),注意一元的减号是会出现的,且字符串中有空格
思路就是使用两个栈,一个储存数字和计算结果,另外一个存运算符。
基本步骤
- 删去括号
- 如果遇到')'就开始计算直到前一个左括号,运算顺序是先出栈的放在后面
遇到的坑
- 减号的优先级是高的,所以遇到减号要直接计算
- 在将字串转化成数字时要先算
s[i]-'0'
,否则可能会超出int范围 - 最简单的处理方法就是在每个新操作前把能算的都算完
tips
为了处理方便,可以在一元'+' 和'-'前面push(0)
具体代码
class Solution {
public:
void cal(stack<int>& numbers, stack<char>& operators){
if(numbers.size()<2||operators.empty()) return;
int num1, num2;
char op;
op=operators.top();
operators.pop();
num2=numbers.top();
numbers.pop();
num1=numbers.top();
numbers.pop();
if(op=='+'){numbers.push(num1+num2);}
else if(op=='-'){numbers.push(num1-num2);}
}
void replace_space(string& s){
int pos=s.find(" ");
while(pos!=-1){
s.replace(pos,1,"");
pos=s.find(" ");
}
}
int calculate(string s) {
stack<int> numbers;
stack<char> operators;
if(s[0]=='-'||s[0]=='+') numbers.push(0);
int num = 0;
replace_space(s);
for (int i = 0; i < s.length();i++) {
if (s[i] >= '0' && s[i] <= '9') {
int number=0;
int j=i;
while(j<s.length()&&s[j]>='0'&&s[j]<='9'){
number=number*10+s[j]-'0';
j++;
}
numbers.push(number);
i=j-1;
}
else if(s[i]==')'){
while(!operators.empty()){
char op=operators.top();
if(op!='(')
cal(numbers,operators);
else{
operators.pop();
break;
}
}
}
else if(s[i]=='(') operators.push(s[i]);
else{
if(i>0&&(s[i-1]=='('||s[i-1]=='+'||s[i-1]=='-')) numbers.push(0);
while (!operators.empty()&&operators.top()!='(')
{
cal(numbers,operators);
}
operators.push(s[i]);
}
}
while(!operators.empty()){
cal(numbers,operators);
}
return numbers.top();
}
};
标签:int,operators,减号,numbers,&&,计算器,push,224,leetcode
From: https://www.cnblogs.com/oxidationreaction/p/18314335