zoukankan      html  css  js  c++  java
  • 224. Basic Calculator

    Implement a basic calculator to evaluate a simple expression string.

    The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

    You may assume that the given expression is always valid.

    Some examples:

    "1 + 1" = 2
    " 2-1 + 2 " = 3
    "(1+(4+5+2)-3)+(6+8)" = 23
    

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

    分析:

     one pass 

    1. curNum  存目前的值

    2. 遇到 + - , res += curNum * sign , sign 存+-

    3.有()用一个stack存目前的res 和sign;

    // res curNum 0 - 9 ; 10 -...
    public class Solution {
        public int calculate(String s) {
            if(s == null || s.length() == 0){
                return 0;
            }
            Stack<Integer> stack = new Stack<>();
            int res = 0;
            int curNum = 0;
            int sign = 1;
            for(int i = 0 ; i < s.length(); i++){
                char temp = s.charAt(i);
                if(temp == ' ') 
                    continue;
                else if(Character.isDigit(temp)) 
                    curNum = curNum * 10 + (int) (temp - '0');
                else if( temp ==  '+'){
                    res += sign * curNum;
                    curNum = 0;
                    sign = 1;
                }
                else if(temp == '-'){
                    res += sign * curNum;
                    curNum = 0;
                    sign = -1;  //prepare for ();
                }
                else if(temp == '('){
                    stack.push(res);
                    stack.push(sign);
                    res = 0;
                    curNum = 0;
                    sign = 1;
                }
                else if(temp == ')'){
                    res += curNum * sign;
                    if(!stack.isEmpty())
                        sign = stack.pop();
                    if(!stack.isEmpty())
                        res = res * sign + stack.pop();
                    curNum = 0;
                    sign = 1;
                }
            }
            if(curNum != 0)
                res += curNum * sign;
                
            return res;
        }
    }
  • 相关阅读:
    css-深入理解margin和padding
    js的自定义事件
    jcFlexible.js的小Demo
    volatile关键字回顾
    threadLocalMap理解
    常用SQL笔记
    MyISAM和innoDB对比,覆盖索引简单回顾
    经典算法回顾:两个队列生成一个栈,两个栈生成一个队列
    Memcached与Redis对比,Redis基础笔记回顾
    ES(ElasticSearch)学习总结
  • 原文地址:https://www.cnblogs.com/joannacode/p/6120496.html
Copyright © 2011-2022 走看看