作者: 柴小喵 Joanna --------- 一只努力码代码的小喵(╹▽╹)
Stack:
本质是list
Stack = []
Stack.append()
Stack.pop()
先进后出
分类讨论-通常考虑要目标/所需的变量/每种情况的处理
Example:
- 嵌套类型
leetcode 394 Decode String:
Input: s = “3[a]2[bc]”
Output: “aaabcbc”
考虑清楚面临的情况/需要的东西/对于每种情况的处理:
数字:需要用一个nums来记录数字,注意有可能有12,13 所以计算公式为nums = nums * 10 + 当前数字
字母:需要一个string来记录字母
左括号:意味着数字和字母的分割,新字母的开始,所以需要将旧字母存入Stack,然后将数字存入,同时需要清零(左括号需要做的事情根据左括号的含义进行理解)
右括号: 说明需要开始重复,需要从stack内pop出数字 * 新字母 + Stack内pop出的旧字母(右括号需要做的事情根据例子进行理解)
for 循环结束, return string就可以了,因为每次结束一定是右括号。
代码:
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
num = 0
string = ""
stack_string_and_number = []
for i in range(len(s)):
if s[i].isdigit():
num = num * 10 + int(s[i])
elif s[i].isalpha():
string += s[i]
elif s[i] == "[": # 新字母的开始,需要将旧的存好,然后清零开始新的字母
stack_string_and_number.append(string)
stack_string_and_number.append(num)
string = ""
num = 0
else: # 需要重复,只需要string, 可以根据Example1 进行理解
number = stack_string_and_number.pop()
old_string = stack_string_and_number.pop()
string = old_string + number * string
return string
- 基本加减乘除
leetcode 227 Basic Calculator II
Input: s = “3+2*2”
Output: 7
面临的情况/需要的东西/对于每种情况的处理:
数字:如果是数字需要用num存起来,注意有可能有12,13 所以计算公式为nums = nums * 10 + 当前数字
操作符:之前的操作符是“ + ”, 存入 “+ num”, 如果之前的操作符是 “-”,存入 “- num”,之前的操作符是“ * ”, 存入 “ pop()* num”,如果之前的操作符是“/”, 需要分类讨论,如果 top = pop() 是非负数或者pop()可以被整除,则存入 “ pop() // num”, 如果是负数且不能被num整除, 则存入”top // num + 1”——>-3//2 + 1= -1(如果是遍历到了最后一个数字,也在这一情况下)
代码:
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
pre_op = '+'
num = 0
for i, each in enumerate(s):
if each.isdigit():
num = 10 * num + int(each)
if i == len(s) - 1 or each in '+-*/':
if pre_op == '+':
stack.append(num)
elif pre_op == '-':
stack.append(-num)
elif pre_op == '*':
stack.append(stack.pop() * num)
elif pre_op == '/':
top = stack.pop()
if top < 0 and -top % num != 0:
stack.append(top // num + 1) # 因为 1-3/2 应该等于0
else:
stack.append(top // num)
pre_op = each
num = 0
return sum(stack)
- Stack 的设计(比如写 Stack的类)(未完待续···)