实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。
示例 1:
输入: “1 + 1”
输出: 2
示例 2:
输入: " 2-1 + 2 "
输出: 3
示例 3:
输入: “(1+(4+5+2)-3)+(6+8)”
输出: 23
说明:
你可以假设所给定的表达式都是有效的。
请不要使用内置的库函数 eval。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/basic-calculator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
//后缀表达式(逆波兰表达式)
public int calculate(String s) {
Stack<Integer> stack1 = new Stack<Integer>();//记录操作数
Stack<Character> stack2 = new Stack<Character>();//记录运算符
stack2.add('#');
int res = 0;
String ss = "";
for(int i=0;i<s.length();i++){
char ch = s.charAt(i);
if(ch==' '){
continue;
}else if(ch=='+' || ch=='-'){
if(!ss.equals("")){
stack1.add(Integer.valueOf(ss));
ss = "";
}
char temp = stack2.peek();
if(temp=='#' || temp=='('){
stack2.add(ch);
}else{
int num2 = stack1.pop();
int num1 = stack1.pop();
if(temp=='+'){
res = num1+num2;
}else if(temp=='-'){
res = num1-num2;
}
stack1.add(res);
stack2.pop();
stack2.add(ch);
}
}else if(ch=='('){
if(!ss.equals("")){
stack1.add(Integer.valueOf(ss));
ss = "";
}
stack2.add(ch);
}else if(ch==')'){
if(!ss.equals("")){
stack1.add(Integer.valueOf(ss));
ss = "";
}
char temp = stack2.pop();
while(temp!='('){
int num2 = stack1.pop();
int num1 = stack1.pop();
if(temp=='+'){
res = num1+num2;
}else if(temp=='-'){
res = num1-num2;
}
stack1.add(res);
temp = stack2.pop();
}
}else{
ss = ss+ch;
}
}
if(!ss.equals("")){
stack1.add(Integer.valueOf(ss));
}
char temp = stack2.pop();
while(temp!='#'){
int num2 = stack1.pop();
int num1 = stack1.pop();
if(temp=='+'){
res = num1+num2;
}else if(temp=='-'){
res = num1-num2;
}
stack1.add(res);
temp = stack2.pop();
}
while(!stack1.isEmpty()){
res = stack1.pop();
}
return res;
}
}
来源:CSDN
作者:皓月v
链接:https://blog.csdn.net/qq_36198826/article/details/103654043