• LeetCode 224. Basic Calculator


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

    题解:

    思路:1. 遇到数字位,看后一位是否为数字,若是位数字,当前位需要进十.

    2. 开始设sign = 1,若遇到 ' - ', sign 改为 -1,若遇到 '+',sign改回1.

    3. 遇到 '(', 压栈,先压之前的res,后压sign,然后初始化res和sign.

    4. 遇到')' ,出栈,当前res先乘pop() 出来的 sign,再加上pop()出来的之前结果.

    5. Encountering space, just continue.

    Note:1.遇到数字时需要生成一个新的cur 用来存储当前数,随后再用cur求res,不能直接求res, '-' 时会出问题.

    Time Complexity: O(s.length()).

    Space: O(s.length()), stack space.

    AC Java: 

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

    类似Evaluate Reverse Polish Notation.

    跟上Basic Calculator II.

  • 相关阅读:
    物料主档的屏幕增强
    删除请求号(网上转载)
    Echarts X轴内容过长自动隐藏,鼠标移动上去显示全部名称方法
    mscms学习
    java 基础(泛型)
    java 基础(枚举类)
    java 基础(抽象类)
    java 基础(单例)
    android项目杂记
    Android Studio--学习系列(3)发版
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825019.html
Copyright © 2020-2023  润新知