Implement a basic calculator to evaluate a simple expression string.
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.
用堆栈来做,注意处理好字符串的空格,和各种CornerCase。思路不复杂,但是细节要注意。
class Solution { public: int calculate(string s) { stack<int> num; stack<char> op; int front = 0; int next = 0; //记录前一个符号和后一个符号 s = '(' + s + ')'; op.push('('); for(int i=1; i<s.size(); i++){ if(s[i]==' ') continue; //空格处理跳过 if(s[i]=='+'||s[i]=='-'||s[i]=='('||s[i]==')'){ next = i; if(!allwhite(s,front,next))//判断两个符号间是否全是空格 num.push(atoi(s.substr(front+1,next-front-1).c_str()));//提取数字 front = next; op.push(s[i]); } if(op.top()==')') // 出栈逻辑 { op.pop(); int temp = 0; while(true) { if(op.top()=='+'){ int a = num.top(); temp = temp + a; num.pop(); op.pop(); } if(op.top()=='-'){ int a = num.top(); num.pop(); temp = temp - a; op.pop(); } if(op.top()=='('){ int a = num.top(); temp = temp + a; num.pop(); num.push(temp); op.pop(); break; } } } } return num.top(); } bool allwhite(string &s,int i,int j){ if(j==i) return true; for(int k=i+1; k<j; k++){ if(s[k]!=' ') return false; } return true; } };