224. Basic Calculator

题目:

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

链接: http://leetcode.com/problems/basic-calculator/

题解:

刚开始以为要用和RPN一样的方法,其实不是的。可以one pass遍历整个数组并且得到结果。 需要使用一个栈来cache括号这种情况。

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0)
            return 0;
        Stack<Integer> stack = new Stack<>();
        int result = 0, curNum = 0, sign = 1;
        
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == ' ')
                continue;
            else if(Character.isDigit(c))
                curNum = curNum * 10 + (int)(c - '0');
            else if (c == '+') {
                result += sign * curNum;
                curNum = 0;
                sign = 1;
            } else if (c == '-') {
                result += sign * curNum;
                curNum = 0;
                sign = -1;
            } else if (c == '(') {
                stack.push(result);
                stack.push(sign);
                curNum = 0;
                sign = 1;
                result = 0;
            } else if (c == ')') {
                result += sign * curNum;
                curNum = 0;
                if(!stack.isEmpty())
                    result *= stack.pop();
                if(!stack.isEmpty())
                    result += stack.pop();
            }
        }
        
        if(curNum != 0)
            result += sign * curNum;
        
        return result;
    }
}

 

Reference:

https://leetcode.com/discuss/39553/iterative-java-solution-with-stack

https://leetcode.com/discuss/41868/java-solution-stack

https://leetcode.com/discuss/39479/simple-c-in-24-ms

 

  

 

posted @ 2015-11-25 07:26  YRB  阅读(706)  评论(0编辑  收藏  举报