Middle-题目99:227. Basic Calculator II

题目原文:
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
“3+2*2” = 7
” 3/2 ” = 1
” 3+5 / 2 ” = 5
题目大意:
计算一个表达式字符串的值,其中含有+,-,*,/,空格和数字
题目分析:
既然用JavaScript的eval水过去会错,那就认真算一下。
首先没有括号,不用考虑括号的问题。那么从左到右先乘除后加减即可。遍历字符串两遍。
源码:(language:java)

public class Solution {
    public int calculate(String s) {
        s=s.replace(" ","");
        String[] nums = s.split("[\\+\\-\\*\\/]");
        List<Integer> numberList = new ArrayList<>();
        for(String num : nums)
            numberList.add(Integer.parseInt(num));
        int index = 0;
        for (int i = 0; i<s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '+' || ch == '-') 
                index++;
            else if (ch == '*' || ch == '/') {
                int op1 = numberList.get(index);
                int op2 = numberList.get(index+1);
                numberList.remove(index);
                numberList.remove(index);
                numberList.add(index, operate(op1,ch,op2));
            }
        }

        int result = numberList.get(0); index = 1;
        for(int i = 0;i<s.length();i++) {
            char ch = s.charAt(i);
            if(ch == '+' || ch == '-') 
                result = operate(result, ch, numberList.get(index++));
        }
        return result;

    }
    private Integer operate(int a, char op, int b) {
        if(op=='+')
            return a+b;
        else if(op=='-')
            return a-b;
        else if(op=='*')
            return a*b;
        else 
            return a/b;
    }
}

成绩:
90ms,beats 13.83%,众数26ms,3.63%
Cmershen的碎碎念:
主要浪费时间还是在split上。

阅读更多
版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs https://blog.csdn.net/cmershen/article/details/51548533
个人分类: Leetcode
上一篇Middle-题目98:316. Remove Duplicate Letters
下一篇Middle-题目100:18. 4Sum
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭