标签:
Java:
1 public class Solution { 2 public int calculate(String s) { 3 if (s == null || s.length() == 0) return 0; 4 Stack<Integer> stack = new Stack<Integer>(); 5 int ans = 0; 6 int sign = 1; 7 for (int i = 0; i < s.length(); i++) 8 { 9 char c = s.charAt(i); 10 if (Character.isDigit(c)) 11 { 12 int cur = c - ‘0‘; 13 while (i+1 < s.length() && Character.isDigit(s.charAt(i+1))) 14 { 15 cur = 10 * cur + s.charAt(++i) - ‘0‘; 16 } 17 ans += sign * cur; 18 } 19 else if (c == ‘-‘) 20 { 21 sign = -1; 22 } 23 else if (c == ‘+‘) 24 { 25 sign = 1; 26 } 27 else if (c == ‘(‘) 28 { 29 stack.push(ans); 30 ans = 0; 31 stack.push(sign); 32 sign = 1; 33 } 34 else if (c == ‘)‘) 35 { 36 ans = stack.pop() * ans + stack.pop(); 37 sign = 1; 38 } 39 } 40 return ans; 41 } 42 }
标签:
原文地址:http://www.cnblogs.com/yingzhongwen/p/4846643.html