LeetCode Basic Calculator II

原题链接在这里:https://leetcode.com/problems/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

Note: Do not use the eval built-in library function.

题解:

Basic Calculator类似。

扫一遍string, 遇到数字计算数字。遇到符号位时先把之前的符号位和当前的数字计算压入stack, 再更改sign, 清空num.

若之前的sign是'*'或者'/'就先pop()出来一个数字与当前数字做相应运算.

最后把stack中逐个数字加入res中.

Time Complexity: O(n). Space: O(n).

AC Java:

 1 public class Solution {
 2     public int calculate(String s) {
 3         if(s == null || s.length() == 0){
 4             throw new IllegalArgumentException("Invalid input string.");
 5         }
 6         
 7         char sign = '+';
 8         int cur = 0;
 9         Stack<Integer> stk = new Stack<Integer>();
10         for(int i = 0; i<s.length(); i++){
11             if(Character.isDigit(s.charAt(i))){
12                 cur = cur*10 + (int)(s.charAt(i)-'0');
13             }
14             
15             if((!Character.isDigit(s.charAt(i)) && s.charAt(i)!=' ') || i==s.length()-1){
16                 if(sign == '-'){
17                     stk.push(-cur);
18                 }else if(sign == '+'){
19                     stk.push(cur);
20                 }else if(sign == '*'){
21                     stk.push(stk.pop()*cur);
22                 }else if(sign == '/'){
23                     stk.push(stk.pop()/cur);
24                 }
25                 sign = s.charAt(i);
26                 cur = 0;
27             }
28         }
29         
30         int res = 0;
31         for(int num : stk){
32             res += num; 
33         }
34         return res;
35     }
36 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825018.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值