LeetCode刷题MEDIM篇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.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

十分钟尝试

没有顺利的思路,看了他人的答案,梳理一下思路,感觉很赞,自己写一下。总体思路是统一按照加法处理,比如3-5,就是+3 与-5求和,把所有的数组都入stack,因为如果是乘法,除法,需要弹出上一个元素。需要注意的是第一个字符如果是int,不能直接入stack,因为有可能是二位数,三位数等等,所以一直处理到不是数字位置。

处理第一个数字----下一个是数字--循环相加

处理第一个数字---下一个不是数字---处理这个输入,根据sign符号,默认为加号--然后sign变为当前的符号,num归零重新计算数值

sign记录的是当前数字前面的符号。

class Solution {
    public int calculate(String s) {
        Deque stack=new LinkedList();
        if(s.length()==0){
            return 0;
        }
        int num=0;
        char preSign='+';
        for(int i=0;i<s.length();i++){
            boolean isDigit=Character.isDigit(s.charAt(i));
            if(isDigit){
                 //是digit,累加
                num=num*10+s.charAt(i)-'0';
            }
            if((!isDigit&&' '!=s.charAt(i))||i==s.length()-1){
                //在后一个不是数字才会把前一个加入stack,所以最后一个数字单独处理
                if(preSign=='+'){
                    stack.push(num);
                }
                 if(preSign=='-'){
                    stack.push(-num);
                }
                 if(preSign=='*'){
                    stack.push((Integer)stack.pop()*num);
                }
                 if(preSign=='/'){
                    stack.push((Integer)stack.pop()/num);
                }
                preSign=s.charAt(i);
                num=0;
            }
            
        }
        int res=0;
        for(int i=0;i<=stack.size();i++){
            res+=(Integer)stack.pop();
        }
        return res;
    }
}

结果不对,stack遍历有问题,stack遍历应该如下写法:

for (Integer e : stack) {
    res += e;
}

但是我的写法问题出在哪里呢?debug 发现popup大过年剩余最后一个元素的时候,,就结束了。

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/86170644