• Basic Calculator 基本计算器-Leetcode


    1.题目:

    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

    题目要求是,实现一个基本的计算器,它接受一个字符串作为输入,实现加法减法和小括号。字符串中有0-9,+,-,(,)和空白符号。

    可以认为所有的计算数均为非负值。可以认为题目的输入均为有效算式。字符串中可能有空格,你需要自己处理掉。

    2.思路:

    递归地计算每个子式相加减的值。

    何为子式?认为整个算式是第一个子式。第一个被括号括起来的式子是第二个子式。依次类推。

    例如,

    (1+(4+5+2)-3)+(6+8)

    中,第一个子式是(1+(4+5+2)-3)+(6+8)。第二个子式是(1+(4+5+2)-3)。第三个是(4+5+2)。第四个是(6+8)。

    那么,

    要求第一个子式的值,就等于求第二个子式+第四个子式。

    要求第二个子式的值,就等于求1+第三个子式-3。

    • 所以,首先要有一个函数1,它接受一个指针指向某个子式的开头,返回这个子式的值。
    • 其次,要有一个函数2,用于把字符串中的1啊,23啊,84啊之类的字符串转换成相应的数值1,23,84。如果要被转换的字符是'(',说明要转换的内容是一个子式,那么就用函数1处理。

    3.代码

    给出一份JAVA实现:

    复制代码
    public class Solution{
        public int calculate(String s){//这个就是函数1
            int ans=0;
            int sign=1;
            while (location<s.length()){
                ans+=(helper(s)*sign);
                if (location>=s.length()) break;
                if (s.charAt(location)==')') {
                    location++;
                    return ans;
                }
                sign=(s.charAt(location)=='-')?-1:1;
                location+=1;
            }
            return ans;
        }
        private int location=0;//这个就是给出子式位置的指针
        private int helper(String s){//这个就是函数2
            int op=0;
            while (location<s.length()&&(Character.isDigit(s.charAt(location))||Character.isSpaceChar(s.charAt(location)))){
                if (Character.isDigit(s.charAt(location))){
                    op*=10;
                    op+=(s.charAt(location)-'0');
                }
                location++;
            }
            if (location<s.length()&&s.charAt(location) == '('){
                location++;
                return calculate(s);
            }
            return op;
        }
    
    }
    复制代码

     

  • 相关阅读:
    jquery实现导航栏切换、下划线移入移出
    兼容:部分iphone手机click事件无效
    解决:TypeError: initAutoImportComponents is not a function 过程记录
    【名词解释】8.序列图
    【名词解释】7.UML类图
    【名词解释】1.懒加载
    【项目】运行jar文件提示没有主清单属性
    【工具】MD5加密
    【工具】【截图工具】FScapture,支持滚动
    【名词解释】repl介绍
  • 原文地址:https://www.cnblogs.com/s844876674/p/4684485.html
Copyright © 2020-2023  润新知