实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。
示例 1:
输入: "1 + 1"
输出: 2
示例 2:
输入: " 2-1 + 2 "
输出: 3
示例 3:
输入: "(1+(4+5+2)-3)+(6+8)"
输出: 23
说明:
你可以假设所给定的表达式都是有效的。
请不要使用内置的库函数 eval。
思路:用栈模拟即可,注意细节
class Solution {
public int calculate(String s) {
if(s.length()==0)
return 0;
Stack<Integer> st1=new Stack<>();
Stack<Object> st2=new Stack<>();
int sum=0;
for(int i=0;i<s.length();i++)
{
if(!st1.isEmpty())
System.out.printf("%d\n", st1.peek());
if(s.charAt(i)==' ')
continue;
if(s.charAt(i)>='0' && s.charAt(i)<='9')
{
sum=sum*10+(s.charAt(i)-'0');
if(i<s.length()-1 && s.charAt(i+1)<='9' && s.charAt(i+1)>='0')
continue;
while(!st2.isEmpty() && (char)st2.peek()!='(')
{
char c=(char)st2.pop();
int x=st1.pop();
if(c=='+')
x=x+sum;
else
x=x-sum;
sum=x;
}
st1.add(sum);
}
else
{
sum=0;
if(s.charAt(i)==')')
{
st2.pop();
while(!st2.isEmpty() && st1.size()>1 && (char)st2.peek()!='(')
{
int y=st1.pop();
int x=st1.pop();
char c=(char)st2.pop();
if(c=='+')
st1.add(x+y);
else
st1.add(x-y);
}
}
else
st2.add(s.charAt(i));
}
}
while(!st2.isEmpty())
{
char c=(char)st2.pop();
int y=st1.pop(),x=st1.pop();
if(c=='+')
st1.add(x+y);
else
st1.add(x-y);
}
return st1.peek();
}
}