basic calculator (stack problem)
2015-06-15 08:21 美女驴 阅读(224) 评论(0) 编辑 收藏 举报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
1 public class Solution { 2 public int calculate(String s) { 3 4 int len = s.length(); 5 Stack<String> stack = new Stack<String>(); 6 int i = 0; 7 while(i < len) 8 { 9 if(s.charAt(i) == ' ') 10 i++; 11 else if (s.charAt(i) == '(' || s.charAt(i) == '+' || s.charAt(i) == '-') 12 { 13 stack.push(s.substring(i,i+1)); 14 i++; 15 } 16 else if(s.charAt(i) >= '0' && s.charAt(i) <= '9') 17 { 18 int start = i; 19 while(i < len && s.charAt(i) >= '0' && s.charAt(i) <= '9') i++; 20 stack.push(s.substring(start, i)); 21 } 22 else 23 { 24 ArrayList<String> tmp = new ArrayList<String>(); 25 while(!stack.empty()) 26 { 27 String top = stack.pop(); 28 if(top.equals("(")) break; 29 tmp.add(0, top); 30 } 31 int sumtmp = 0; 32 sumtmp += Integer.valueOf(tmp.get(0)); 33 for(int j = 1; j < tmp.size(); j=j+2) 34 { 35 if(tmp.get(j)=="-") 36 sumtmp -= Integer.valueOf(tmp.get(j+1)); 37 else 38 sumtmp += Integer.valueOf(tmp.get(j+1)); 39 } 40 stack.push(Integer.toString(sumtmp)); 41 i++; 42 } 43 } 44 ArrayList<String> tmp = new ArrayList<String>(); 45 while(!stack.empty()) 46 { 47 String top = stack.pop(); 48 tmp.add(0, top); 49 } 50 int result = 0; 51 result += Integer.valueOf(tmp.get(0)); 52 for(int j = 1; j < tmp.size(); j=j+2) 53 { 54 if(tmp.get(j)=="-") 55 result -= Integer.valueOf(tmp.get(j+1)); 56 else 57 result += Integer.valueOf(tmp.get(j+1)); 58 } 59 return result; 60 } 61 }
从25 到 30这段代码,i.e.,
while(!stack.empty()) { String top = stack.pop(); if(top.equals("(")) break; tmp.add(0, top); }
为什么不能写成这样
while(stack.peek()!="(") { String top = stack.pop(); tmp.add(0, top); }
写成这样就会报错
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)
可是我能确定执行这段代码时stack是不为空的啊~