[LeetCode] 224. Basic Calculator
阿新 • • 發佈:2018-12-10
Problem
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 .
Example 1:
Input: "1 + 1"
Output: 2
Example 2:
Input: " 2-1 + 2 "
Output: 3
Example 3:
Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23
Note:You may assume that the given expression is always valid.Do not use the eval built-in library function.
Solution
class Solution { public int calculate(String s) { s = s.trim().replaceAll(" ", ""); Stack<Integer> stack = new Stack<>(); int sign = 1, res = 0; System.out.println(s); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == '+') { sign = 1; } else if (ch == '-') { sign = -1; } else if (ch == '(') { stack.push(res); stack.push(sign); res = 0; sign = 1; } else if (ch == ')') { res *= stack.pop(); res += stack.pop(); } else { int sum = 0; while (i < s.length() && Character.isDigit(s.charAt(i))) { sum = sum*10 + (s.charAt(i)-'0'); i++; } res += sum*sign; i--; } } return res; } }