版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/85123486
一开始我想的是跟Ⅱ的做法差不多,但是Ⅱ的做法有个缺陷,就是只有最后才能得到加在一起的结果,对于括号内的算式而言,也没有办法像Ⅰ一样一次就算出全部的结果形成一个操作数,除非在栈内标识出括号的边界。可是这样一来就变得非常复杂。
所以这个题使用了递归,一个值得注意的处理方法时对于嵌套括号的算式如何找到每个'('对应的')',用一个变量cnt,遇到左括号自增1,遇到右括号自减1,当cnt为0的时候,说明括号正好完全匹配。
class Solution {
public:
int calculate(string s) {
set<char> numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
stack<int> ns;
int res=0;
int index = 0;
int op=1;
if (!s.empty())
{
while ((index = s.find(' ', index)) != string::npos)
s.erase(index, 1);
}
int i=0;
int cal=0;
int bracket=0;
while (i<s.length())
{
if (numbers.count(s[i]) != 0)
{
cal = s[i] - 48;
while (numbers.count(s[i + 1]) != 0)
{
cal = cal * 10 + s[i + 1] - 48;
i++;
}
if (op==1) ns.push(cal);
else if (op==2) ns.push(-1*cal);
else if (op==3){int a=ns.top(); ns.pop(); ns.push(a*cal);}
else if (op==4){int a=ns.top(); ns.pop(); ns.push(a/cal);}
}
else if (s[i]=='-') op=2;
else if (s[i]=='+') op=1;
else if (s[i]=='*') op=3;
else if (s[i]=='/') op=4;
else if (s[i]=='(')
{
int j=i;int cnt=0;
for (j;j<s.length();j++)
{
if (s[j]=='(') cnt++;
if (s[j]==')')cnt--;
if (cnt==0) break;
}
cal=calculate(s.substr(i + 1, j- i - 1));
if (op==1) ns.push(cal);
else if (op==2) ns.push(-1*cal);
else if (op==3){int a=ns.top(); ns.pop(); ns.push(a*cal);}
else if (op==4){int a=ns.top(); ns.pop(); ns.push(a/cal);}
i=j;
}
i++;
}
while (!ns.empty())
{
res=res+ns.top();
ns.pop();
}
return res;
}
};