Calculator| ||




总算找到这题正确的,便于理解的方法了。
iterative, stack, 括号 
好好体会这三者到联系。
  public int calculate(String s) {
        s = s.replace(" ","");
        int res = 0;
        int sign = 1;
        Stack
    
    
     
      resStack = new Stack<>();
        Stack
     
     
      
       signs = new Stack<>();
        int i = 0;
        while(i
      
      
       
       0){
                    res = res*signs.pop() +  resStack.pop();
                }
                i++;
            }
        }
        return res;
    }
      
      
     
     
    
    


要是被考这种题目,也是醉了。太个例了。这个方法是我找到最简单的一种实现,也好理解,记住吧。以后再做不要浪费时间了。

核心思路(code ganker method):
我们只能加入之前的数,不能加之后的,因为我们不知道之后的会不会有乘法。遇到乘除更新之前的数,不然就向结果加入之前的数,然后更新之前的数为当前的数。这里要把正负记在数里,因为operator的信息接着会被抹掉。
以 2 - 3+3*3 为例
当扫到 ‘-‘,我们previous value是2, res + 2, 更新prev value
当扫到’+‘, 我们previous value是-3, res + (-3)更新 prev value
当扫到’*‘, 我们previous value是 3,更新之为 3*3  

扫完了最后加上最后一个prev value  res + 3*3

上面的方法代码简单但是思维逆向。是按照计算机的逻辑思考。

 //update my version
 public class Solution {
    public int calculate(String s) {
        s = s.replaceAll(" ","");
        char[] sc = s.toCharArray();
        HashSet
   
   
    
     opts = new HashSet
    
    
     
     ();
        opts.add('+');
        opts.add('-');
        opts.add('*');
        opts.add('/');
        Stack
     
     
      
       stack = new Stack
      
      
       
       ();
        int i = 0;
        while(i
       
       
         opts){ int res = s.charAt(i++) - '0'; while(i 
        
          =0){ cur_value = 10*cur_value + s.charAt(i) - '0'; i++; } if(prev_op == '+'){ res += prev_value; prev_value = cur_value; } if(prev_op == '-'){ //pay attention here. We can only add previous value to res safely, the previous value could be either positive //or negative. //Notice, the previous operator deicde current value to be positive or negative. //the previous previous operator decide previous value's positiveness. //when we deal previous value, we already override previous previous operator, that's why //we must incorporate its information into the value(current value at that time) when we still have it. res += prev_value; prev_value = -cur_value; } if(prev_op == '*'){ prev_value *= cur_value; } if(prev_op == '/'){ prev_value /= cur_value; } if(i < s.length()) prev_op = s.charAt(i); i++; } res += prev_value; return res; } } 
         
       
      
      
     
     
    
    
   
   


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值