解题思路
还是用栈
提交代码
class Solution {
public int calculate(String s) {
int res=0,p=0,num=0,tmp=0,flag=1;
Stack<Integer> stack=new Stack<Integer>();
while(p<s.length()) {
if(s.charAt(p)>='0'&&s.charAt(p)<='9') {
num=s.charAt(p)-'0';
while(p+1<s.length()&&s.charAt(p+1)>='0'&&s.charAt(p)<='9') {
num*=10;
num+=s.charAt(p+1)-'0';
p++;
}
stack.push(flag*num);
flag=1;
}else if(s.charAt(p)=='-') {
flag=-1;
}else if(s.charAt(p)=='*') {
while(s.charAt(p+1)==' ') p++;
tmp=s.charAt(++p)-'0';
while(p+1<s.length()&&s.charAt(p+1)>='0'&&s.charAt(p+1)<='9') {
tmp*=10;
tmp+=s.charAt(++p)-'0';
}
res=stack.pop()*tmp;
stack.push(res);
}else if(s.charAt(p)=='/') {
while(s.charAt(p+1)==' ') p++;
tmp=s.charAt(++p)-'0';
while(p+1<s.length()&&s.charAt(p+1)>='0'&&s.charAt(p+1)<='9') {
tmp*=10;
tmp+=s.charAt(++p)-'0';
}
res=stack.pop()/tmp;
stack.push(res);
}
p++;
}
res=0;
while(!stack.isEmpty())
res+=stack.pop();
return res;
}
}
运行结果

本文介绍了一种使用栈数据结构来解析和计算包含加减乘除运算的数学表达式的方法。通过逐字符扫描输入字符串,利用栈来暂存数字和运算符,实现了表达式的正确解析与计算。
1320

被折叠的 条评论
为什么被折叠?



