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上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值