Implement a basic calculator to calculate the value of a simple string expression.
String expressions can contain opening parentheses (
, closing parentheses )
, plus +
, minus, nonnegative integers, -
and spaces
.
Example 1:
Input: "1 + 1" Output: 2
Example 2:
Input: "2-1 + 2" output: 3
Example 3:
Input: "(1+ (4+5+2)-3) + (6+8)" Output: 23
Description
- You can assume that the given expression is valid.
- Please do not use the built-in library functions
eval
.
The code to write at the beginning is as follows, too redundant:
classSolution { Public: intCalculatestrings) {stack<int>S1; Stack<Char>S2; intCurres =0; for(inti =0; I <s.size ();) { if(S[i] = =' ') {i++; } Else if(S[i] = ='+'|| S[i] = ='-'|| S[i] = ='(') {S2.push (s[i++]); } Else if(IsDigit (S[i])) {intTMP =0, j =i; while(J < S.size () &&isdigit (S[j])) {tmp=Ten* tmp + s[j++]-'0'; } s1.push (TMP); I=J; if(!s2.empty () && s2.top ()! ='(') { CharCtmp =S2.top (); S2.pop (); intsecond, first; Second=S1.top (); S1.pop (); First=S1.top (); S1.pop (); Curres= Ctmp = ='+'? First + Second:first-second; S1.push (Curres); } } Else{s2.pop ();//( CharOP ='?'; intFirst =0, second; if(!S2.empty ()) {op=S2.top (); S2.pop (); Second=S1.top (); S1.pop (); if(!S1.empty ()) { First=S1.top (); S1.pop (); } if(OP = ='+') {S1.push ( first+second); } Else if(OP = ='-') {S1.push ( first-second); } Else{S1.push (second); }} I++; } } returnS1.empty ()?0: S1.top (); }};
Later on the internet found a more concise wording, reference https://www.cnblogs.com/newnoobbird/p/9627182.html. Very concise, the use of
classSolution { Public: intCalculatestrings) {intres=0, sign=1, n=s.size (); Stack<int>St; for(intI=0; i<n;i++){ if(s[i]>='0'){ intnum=0; while(i<n&&s[i]>='0') {num=num*Ten+s[i++]-'0'; } Res+=sign*num; I--; }Else if(s[i]=='+') { sign=1; }Else if(s[i]=='-') { sign=-1; }Else if(s[i]=='(') {St.push (res); St.push (sign); Res=0; sign=1; }Else if(s[i]==')') {res*=st.top (); St.pop (); Res+=st.top (); St.pop (); } } returnRes; }};
Leetcode 224. Basic Calculator