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

    链接: http://leetcode.com/problems/basic-calculator/

    题解:

    刚开始以为要用和RPN一样的方法,其实不是的。可以one pass遍历整个数组并且得到结果。 需要使用一个栈来cache括号这种情况。

    Time Complexity - O(n), Space Complexity - O(n)。

    public class Solution {
        public int calculate(String s) {
            if(s == null || s.length() == 0)
                return 0;
            Stack<Integer> stack = new Stack<>();
            int result = 0, curNum = 0, sign = 1;
            
            for(int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(c == ' ')
                    continue;
                else if(Character.isDigit(c))
                    curNum = curNum * 10 + (int)(c - '0');
                else if (c == '+') {
                    result += sign * curNum;
                    curNum = 0;
                    sign = 1;
                } else if (c == '-') {
                    result += sign * curNum;
                    curNum = 0;
                    sign = -1;
                } else if (c == '(') {
                    stack.push(result);
                    stack.push(sign);
                    curNum = 0;
                    sign = 1;
                    result = 0;
                } else if (c == ')') {
                    result += sign * curNum;
                    curNum = 0;
                    if(!stack.isEmpty())
                        result *= stack.pop();
                    if(!stack.isEmpty())
                        result += stack.pop();
                }
            }
            
            if(curNum != 0)
                result += sign * curNum;
            
            return result;
        }
    }

    Reference:

    https://leetcode.com/discuss/39553/iterative-java-solution-with-stack

    https://leetcode.com/discuss/41868/java-solution-stack

    https://leetcode.com/discuss/39479/simple-c-in-24-ms

      

  • 相关阅读:
    django中的分页管理
    python 时间字符串和时间戳之间的转换
    随机生成英文字母,并且统计频数
    html 中a标签的问题(无反应,跳转,调用方法)
    oracle sid,instance_name,db_name,oracle_sid之间的关系
    备份
    修改yum源
    sql基本语法
    第二章 shell编程基础
    第一章 初识shell程序
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4993541.html
Copyright © 2011-2022 走看看