码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Basic Calculator II

时间:2015-12-06 09:56:33      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

public class Solution {
    public int calculate(String s) {
        Stack<String> stack = new Stack<String>();
        s = s.replace(" ", "");
        int length = s.length();
        int index = 0;
        if (s.charAt(0) <= ‘9‘ && s.charAt(0) >= ‘0‘)
            stack.push("+");
        while (index < length) {
            char ch = s.charAt(index);
            if (ch > ‘9‘ || ch < ‘0‘) {
                if (ch == ‘+‘ || ch == ‘-‘) {
                    stack.push(String.valueOf(ch));
                    index ++;
                } else {
                    int first = Integer.valueOf(stack.pop());
                    int tmp = index;
                    index = helper(s, index + 1);
                    int second = Integer.valueOf(s.substring(tmp + 1, index));
                    if (ch == ‘*‘) {
                        stack.push(String.valueOf(first * second));
                    } else {
                        stack.push(String.valueOf(first / second));
                    }
                }
            } else {
                int tmp = index;
                index = helper(s, index + 1);
                stack.push(s.substring(tmp, index));
            }
        }
        int result = 0;
        while (!stack.isEmpty()) {
            int tmp = Integer.valueOf(stack.pop());
            int positive = stack.pop().equals("+") ? 1 : -1;
            result += tmp * positive;
        }
        return result;
    }
    public int helper(String s, int index) {
        while(index < s.length() && s.charAt(index) <= ‘9‘ && s.charAt(index) >= ‘0‘) {
            index ++;
        }
        return index;
    }
}

 

[LeetCode]Basic Calculator II

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5022848.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!