Leetcode 224. 基本计算器
题目
实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。
测试样例
示例 1:
输入: "1 + 1"
输出: 2
示例 2:
输入: " 2-1 + 2 "
输出: 3
示例 3:
输入: "(1+(4+5+2)-3)+(6+8)"
输出: 23
说明:
- 你可以假设所给定的表达式都是有效的。
- 请不要使用内置的库函数 eval。
题解
利用栈
本题情况相对简单,只需要考虑+、-、(、)情况,显然(优先级最大,)优先级最低,+、-优先级相同。因此,如果是(直接入符号栈;)则进行栈中符号的运算,同时弹出(;+、-则需要判定栈中是否为(,不是则进行运算。详细过程见代码
代码
int calculate(string s) {
stack<long> conclude; //数字栈
stack<char> fuhao; //符号栈
int i=0,len=s.length();
while(i<len){
if(s[i] == ' ') i++;
else if(s[i] == '('){ //(直接入栈
fuhao.push('(');
i++;
}
else if(s[i] == ')'){
if(fuhao.top() != '('){ //栈中有符号则进行运算
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if(fuhao.top() == '+') conclude.push(y+x);
else conclude.push(y-x);
fuhao.pop(); //弹出(
}
fuhao.pop();
i++;
}else if(s[i] == '+' || s[i]=='-'){
if(!fuhao.empty() && fuhao.top() != '('){ //栈中优先级和+、-相同则进行运算
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if(fuhao.top() == '+') conclude.push(y+x);
else conclude.push(y-x);
fuhao.pop();
}
fuhao.push(s[i]);
i++;
}else{ //获取数,并压入数字栈中
long x=s[i]-'0';
i++;
while(i<len && s[i]<='9' && s[i]>='0'){
x = x*10 + (s[i]-'0');
i++;
}
conclude.push(x);
}
}
if(!fuhao.empty()){ //最后一次运算
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if(fuhao.top() == '+') conclude.push(y+x);
else conclude.push(y-x);
fuhao.pop();
}
return conclude.top();
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/basic-calculator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。