标签:
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
Note: Do not use the eval
built-in library function.
这个问题应该是比较亲切了!但是任然出现了超时问题,原因在于list的使用,list是使用链表实现的,随机存取效率不高,在这里当数据量比较大的时候,效率骤降,改用vector作为存储的基本单位。
代码如下:
1 import java.util.*; 2 3 public class Solution { 4 //使用list效率应该是更低一些,在这里竟然会超时!!!!!!!!!!! 5 //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 6 private Vector<String> getSeg(String s){ 7 s=s.trim(); 8 Vector<String> segment = new Vector<String>(); 9 int pre=0,i=0; 10 while(i<s.length()){ 11 char c=s.charAt(i); 12 switch(c){ 13 case ‘ ‘: 14 i++; 15 break; 16 case ‘(‘: 17 case ‘)‘: 18 case ‘+‘: 19 case ‘-‘: 20 segment.add(s.substring(i,i+1)); 21 i++; 22 break; 23 default: 24 int endindex=i+1; 25 while(endindex<s.length()&&Character.isDigit(s.charAt(endindex))){ 26 endindex++; 27 } 28 segment.add(s.substring(i,endindex)); 29 i=endindex; 30 break; 31 } 32 } 33 return segment; 34 } 35 public int calculate(String s) { 36 Stack<Character> op = new Stack<Character>(); 37 Stack<Integer> data = new Stack<Integer>(); 38 Vector<String> segments = getSeg(s); 39 for(int i=0;i<segments.size();i++){ 40 String seg = segments.get(i); 41 int opc = seg.charAt(0); 42 if(opc<=‘9‘&&opc>=‘0‘){ 43 data.push(Integer.parseInt(seg)); 44 }else{ 45 switch(opc){ 46 case ‘(‘: 47 op.push((char)opc); 48 break; 49 case ‘-‘: 50 case ‘+‘: 51 if(!op.isEmpty()&&op.peek()!=‘(‘){ 52 int data1 = data.pop(); 53 int data2 = data.pop(); 54 char opthis = op.pop(); 55 int resdata = 0; 56 if(opthis==‘+‘) resdata = data1 + data2; 57 else resdata = data2 - data1; 58 data.push(resdata); 59 } 60 op.push((char)opc); 61 break; 62 case ‘)‘: 63 while(op.peek()!=‘(‘){ 64 int data1 = data.pop(); 65 int data2 = data.pop(); 66 char opthis = op.pop(); 67 int resdata = 0; 68 if(opthis==‘+‘) resdata = data1 + data2; 69 else resdata = data2 - data1; 70 data.push(resdata); 71 } 72 op.pop(); 73 break; 74 } 75 } 76 } 77 while(!op.isEmpty()){ 78 int data1 = data.pop(); 79 int data2 = data.pop(); 80 char opthis = op.pop(); 81 int resdata = 0; 82 if(opthis==‘+‘) resdata = data1 + data2; 83 else resdata = data2 - data1; 84 data.push(resdata); 85 } 86 return data.pop(); 87 } 88 }
标签:
原文地址:http://www.cnblogs.com/deepblueme/p/4773955.html