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
1 Public classSolution {2 Public intCalculate (String s) {3 4 intLen =s.length ();5stack<string> stack =NewStack<string>();6 inti = 0;7 while(I <len)8 {9 if(S.charat (i) = = ") Teni++; One Else if(S.charat (i) = = ' (' | | | S.charat (i) = = ' + ' | | S.charat (i) = = '-') A { -Stack.push (S.substring (i,i+1)); -i++; the } - Else if(S.charat (i) >= ' 0 ' && s.charat (i) <= ' 9 ') - { - intStart =i; + while(I < len && S.charat (i) >= ' 0 ' && s.charat (i) <= ' 9 ') i++; - Stack.push (s.substring (Start, i)); + } A Else at { -arraylist<string> tmp =NewArraylist<string>(); - while(!stack.empty ()) - { -String top =Stack.pop (); - if(Top.equals ("(")) Break; inTmp.add (0, top); - } to intsumtmp = 0; +Sumtmp + = integer.valueof (tmp.get (0)); - for(intj = 1; J < Tmp.size (); J=j+2) the { * if(Tmp.get (j) = = "-") $Sumtmp-= integer.valueof (Tmp.get (j+1));Panax Notoginseng Else -Sumtmp + = integer.valueof (Tmp.get (j+1)); the } + Stack.push (integer.tostring (sumtmp)); Ai++; the } + } -arraylist<string> tmp =NewArraylist<string>(); $ while(!stack.empty ()) $ { -String top =Stack.pop (); -Tmp.add (0, top); the } - intresult = 0;WuyiResult + = integer.valueof (tmp.get (0)); the for(intj = 1; J < Tmp.size (); J=j+2) - { Wu if(Tmp.get (j) = = "-") -Result-= Integer.valueof (Tmp.get (j+1)); About Else $Result + = Integer.valueof (Tmp.get (j+1)); - } - returnresult; - } A}
From 25 to 30 this code, i.e,
while (! Stack.empty ()) { = stack.pop (); if Break ; Tmp.add (0, top); }
Why can't it be written like this
while (Stack.peek ()! = "(") {= stack.pop (); Tmp.add (0, top); }
Written like this will be an error
Exception in thread "main" java.util.EmptyStackException
At Java.util.Stack.peek (stack.java:102)
At Helloworld.calculate (helloworld.java:43)
At Helloworld.main (helloworld.java:83)
But I can be sure that the stack is not empty when executing this code.
Basic calculator (stack problem)