标签:
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
Simple iterative solution by identifying characters one by one. One important thing is that the input is valid, which means the parentheses are always paired and in order. Only 5 possible input we need to pay attention:
Finally if there is only one number, from the above solution, we haven‘t add the number to the result, so we do a check see if the number is zero.
public class Solution { public int calculate(String s) { int number = 0; int result = 0; int sign = 1; Stack<Integer> stack = new Stack<Integer>(); for(int i=0;i<s.length();i++) { char c = s.charAt(i); if(Character.isDigit(c)) { number = number * 10 + (c-‘0‘); } else if (c==‘+‘) { result += sign*number; number = 0; sign = 1; } else if (c==‘-‘) { result += sign*number; number = 0; sign = -1; } else if (c==‘(‘) { stack.push(result); stack.push(sign); result = 0; sign = 1; } else if (c==‘)‘) { result += sign*number; number = 0; result *= stack.pop(); result += stack.pop(); } } if(number != 0) result += sign * number; return result; } }
reference: https://leetcode.com/discuss/39553/iterative-java-solution-with-stack
标签:
原文地址:http://www.cnblogs.com/hygeia/p/5135534.html