The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval
built-in library function.
想法一:首先计算出每个小括号内的值,一层一层解锁小括号内的值,比如:
s = (1+(4+5+2)-3)+(6+8),首先逐步遍历,找第一对配对的小括号:(4+5+2),计算其值为:11,将此部分替换为11: s = (1+11-3)+(6+8);找到第二对配对的小括号:(1+11-3),计算其值为:9,将此部分替换为9: s = 9+(6+8);找到第三对配对的小括号:(6+8),计算其值为:14,将此部分替换为14:s = 9+14;最后计算s的值等于23.
基于上述思想的代码为:
class Solution { public: int calculate(string s) { int ans = 0; stack<int> parentheses; for(int i =0 ;i<s.size();i++){ if(s[i]=='(') parentheses.push(i); else if(s[i]==')'){ int j = parentheses.top(); string t = itoa(calculate(s.substr(j+1,i-j-1))); s=s.substr(0,j)+t+s.substr(i+1); i = j+t.size()-1; parentheses.pop(); } } if(parentheses.empty()){ for(int i=s.size()-1;i>0;i--){ if(s[i]=='+') { ans+=atoi(s.substr(i+1).c_str()); s = s.substr(0,i); } else if(s[i]=='-'){ if(i!=0 && s[i-1]=='-'){ ans+=atoi(s.substr(i+1).c_str()); s = s.substr(0,i-1); } else{ ans-=atoi(s.substr(i+1).c_str()); s = s.substr(0,i); } } } ans+=atoi(s.c_str()); } return ans; } string itoa(int i){ stringstream ss; string s; ss<<i; ss>>s; return s; } };
想法二:从头到尾遍历字符串,一次处理每个字符。
首先定义两个栈nums和ops,分别储存数字和符号。定义int num存储一个连续的数字,定义int rest存储小括号内表达式的值,定义sign储存当前符号。从头到尾遍历字符串,一次处理每个字符:如果该字符是数字,那么存储在num中,如果不是数字,有4种情况:是‘+’:将当前符号sign置为1,
是‘-’:将当前符号sign置为-1;
是‘(’,说明开始计算一个新的小括号表达式,将rest存入nums,将sign存入ops,然后置rest=0,sign=1;
是‘)’,说明一个小括号表达式计算完毕,那么此时rest=rest*ops.top()+nums.top(),也就是说:小括号内的值为rest,小括号前的符号为ops.top(),小括号前面的字符串的值为nums.top(),此时的rest就等于当前位置到字符串首的计算值;然后弹出栈nums.pop(),ops.pop();
class Solution { public: int calculate(string s) { stack<int> nums,ops; int sign=1; int num=0;//每个数 int rest = 0;//每个小括号内的数 for(auto c:s){ if(isdigit(c)){ num = num*10+c-'0'; } else{ rest += sign*num; num = 0;//处理下一个数,num置0 if(c=='-') sign=-1; if(c=='+') sign=1; if(c=='('){//处理下一个小括号内的数 rest置0 nums.push(rest); ops.push(sign); rest = 0; sign = 1; } if(c==')'){ if(nums.size()){ rest = rest*ops.top()+nums.top(); ops.pop(); nums.pop(); } } } } return rest+sign*num; } };