LeetCode解题 Day11

224. Basic Calculator

https://leetcode.com/problems/basic-calculator/


题目解释

你会得到一个字串s ,这个字串是一组算式,请回传算式计算的结果

example

https://i.imgur.com/EzRc51S.png

解法

这题比较麻烦的是它有括号需要处理,幸运的是他的字串不会出现乘除;因此,括号前面的负号是我们要烦恼的

这题的解法是用堆叠(stack),把目前累积的结果和括号前面的正负号储存起来

等括号内的计算完成後,就把存起来的东西取出来并加在目前累积的结果

程序码

class Solution:
    def calculate(self, s: str) -> int:
        
        stack = []
        operation = '+' 
        num = 0
        ans = 0
        
        for i in range(len(s)):
            current = s[i]
            
            if current.isdigit():
                num = num * 10 + int(current)
            
            elif current in '+-':
                
                if operation == '+':
                    ans += num
                else:
                    ans -= num
                
                operation = current
                num = 0
            
            elif current == '(':
                stack.append(ans)
                stack.append(operation)
                operation = '+'
                num = 0
                ans = 0
            
            elif current == ')':
                
                if operation == '+':
                    ans += num
                else:
                    ans -= num
                
                operation = stack.pop()
                if operation == '-':
                    ans *= -1
                ans += stack.pop()
                num = 0
        
        
        if operation == '+':
            ans += num
        else:
            ans -= num
        return ans

不过这样的程序码不好修改成能处理乘除法

所以比较好的解答,应该是要在遇到括号时就呼叫自己(self.calculate),并个别回传括号内的结果


闲聊

今天的题目因为不用处理乘除所以还算简单

大学刚学stack时也有练习过类似的题目

话说这两天有台风要来了,大家注意平安和防水罗!


<<:  案例:在AWS上透过SageMaker跟CodePipeline驾驭MLOps的参考架构(下)

>>:  [Day7] struct 结构体

[Flutter ] 为Flutter 建立 Django 资料库

version: python 3.8.3 django 3.2.4 建立名为 NOTES,APP名...

Day 27 - 成本估计与 Amazon DynamoDB

Day 27 - 成本估计与 Amazon DynamoDB 观赏鱼辨识成本估计 根据 观赏鱼辨识系...

Android Studio初学笔记-Day7-Button和Toast

Button和Toast 今天要介绍的是Button这个常在程序中能看到的元件,在Button的属性...

33岁转职者的前端笔记-DAY 22 成绩计算机练习笔记

流程 1.先观察画面,哪些值需要抓 2.抓HTML的值: a.先宣告变数,变数就是抓HTML的值,也...

NestJs 延伸篇 - Gateway 与 前端接通

Gateway 与 前端接通 最後我们来测试,由前端接 gateway 取得後端资料 我的 gate...