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-negati ve integers and empty spaces
.
Assume that the given expression was always valid.
Some Examples:
"1 + 1" = 2 "2-1 + 2" = 3 "(1+ (4+5+2)-3) + (6+8)" = 23
A basic calculator, you can use two stacks to solve, the following method is to refer to other people's practice, when you encounter the opening parenthesis to consider the first thing in parentheses, so the previous results all into the stack. When the closing parenthesis is encountered, the stack's contents before the opening parenthesis are calculated to get the temporary result again. here because
After that there is a + and minus sign, so you can use sign = =-to simulate minus. The res here actually corresponds to the role of a stack:
1 classSolution {2 Public:3 intCalculatestrings) {4 intSZ =s.size ();5 intLeft , right;6 CharOptor ='0';7stack<int> TOKENSTK;//Note that this is int8 intres =0;9 intSign =1;Ten for(inti =0; I < sz; ++i) { One if(S[i] = ='+') ASign =1; - Else if(S[i] = ='-') -Sign =-1; the Else if(IsDigit (S[i])) { - intTmpnum =0; - for(intj = i; J < Sz; ++j) { - if(IsDigit (S[j])) { +Tmpnum *=Ten; -Tmpnum + = (S[j]-'0'); +i =J; A}Else Break; at } -Res + = sign *Tmpnum; -}Else if(S[i] = ='('){ - Tokenstk.push (res); -res =0; - Tokenstk.push (sign); inSign =1; -}Else if(S[i] = =')'){ to intTmpsign =tokenstk.top (); + Tokenstk.pop (); - intleft =tokenstk.top (); the Tokenstk.pop (); *res = res * tmpsign +Left ; $Sign =1;Panax Notoginseng } - } the returnRes; + } A};
Leetcode oj:basic Calculator (Basic calculator)