224. Basic Calculator
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
解题思路:信晴神,得永生。
class Solution { public: struct node{ int num; char op; bool flag; }; void change(string str){ double num; node temp; for(int i=0;i<str.length();){ if(str[i]==' '){ i++; continue; } if(isdigit(str[i])){ temp.flag=true; temp.num=str[i++]-'0'; while(i<str.length()&&isdigit(str[i])){ temp.num=temp.num*10+str[i++]-'0'; } q.push(temp); } else { temp.flag=false; if(str[i]=='(') temp.op=str[i],s.push(temp); else if(str[i]==')'){ while(!s.empty()&&(s.top().op!='(')){ q.push(s.top());s.pop(); } if(!s.empty())s.pop(); } else { while(!s.empty()&&(s.top().op!='(')){ q.push(s.top());s.pop(); } temp.op=str[i]; s.push(temp); } i++; } } while(!s.empty()){ q.push(s.top()); s.pop(); } } int calculate(string str) { change(str); // cout<<q.size()<<endl; if(q.size()==1)return q.front().num; int temp1,temp2; node cur,temp; while(!q.empty()){ cur=q.front(); q.pop(); if(cur.flag)s.push(cur); else { temp2=s.top().num; s.pop(); temp1=s.top().num; s.pop(); temp.flag=true; if(cur.op=='+')temp.num=temp1+temp2; else if(cur.op=='-')temp.num=temp1-temp2; // cout<<temp.num<<endl; s.push(temp); } } return s.top().num; } private: stack<node>s; queue<node>q; };