LeetCode Basic Calculator II

来源:互联网 发布:java开源微信公众平台 编辑:程序博客网 时间:2024/05/08 14:28

原题链接在这里:https://leetcode.com/problems/basic-calculator-ii/

Basic Calculator类似。

思路: 扫一遍string,遇见数字时看栈顶是不是 '*' 或者 '/',若不是,就压栈,若是就取出栈顶两个元素算结果,再押回栈。

遇见符号就压栈。

基本就是先算了 乘除运算。

剩下栈里的就是加减运算了。这里注意需用到翻转栈, 使用了 Collections.reverse(stk).

Time O(n), Space O(n).

AC Java:

public class Solution {    public int calculate(String s) {        if(s == null || s.length() == 0 ){            return Integer.MIN_VALUE;        }        int res = 0;        Stack<Integer> stk = new Stack<Integer>();                for(int i = 0; i<s.length(); i++){            if(Character.isDigit(s.charAt(i))){                int cur = (int)(s.charAt(i)-'0');                while((i+1)<s.length() && Character.isDigit(s.charAt(i+1))){                    cur = cur*10 + (int)(s.charAt(i+1) - '0');                    i++;                }                if(!stk.empty() && (stk.peek() == Integer.MIN_VALUE+2 || stk.peek() == Integer.MIN_VALUE+3)){                    if(stk.peek() == Integer.MIN_VALUE+2){                        stk.pop();                        cur = stk.pop()*cur;                        stk.push(cur);                    }                    if(stk.peek() == Integer.MIN_VALUE+3){                        stk.pop();                        cur = stk.pop()/cur;                        stk.push(cur);                    }                }else{                    stk.push(cur);                }                            }else{                switch(s.charAt(i)){                    case '+':                        stk.push(Integer.MIN_VALUE);                        break;                    case '-':                        stk.push(Integer.MIN_VALUE+1);                        break;                    case '*':                        stk.push(Integer.MIN_VALUE+2);                        break;                    case '/':                        stk.push(Integer.MIN_VALUE+3);                        break;                    default:                        continue;                }            }                    }        if(stk.empty())             return res;        Collections.reverse(stk);   //error        res = stk.pop();        while(!stk.empty()){            int oper = stk.pop();            int num = stk.pop();            if(oper == Integer.MIN_VALUE){                res += num;            }else{                res -= num;            }        }        return res;    }}



0 0
原创粉丝点击