zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    gitlab centos 安装配置运维笔记
    CentOS 7 升级内核 Kernel
    VMware 桥接模式 复制物理网络连接状态的作用
    diskpart setid value list
    怎样判断Windows的DPI大小?
    Camtasia Studio 6录制视频时鼠标闪烁的解决办法
    ssh的各个jar包作用
    MyEclipse优化技巧
    Struts详细用法
    Ajax的readyState和status属性
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825019.html
Copyright © 2011-2022 走看看