class Solution:
### 0203 辅助栈(40 ms,14.9 MB)
def decodeString(self, s: str) -> str:
stack, res, multi = [], '', 0
for c in s:
# 若当前字符为[,则入栈
# 注意:需重置res和multi,保存新的子串!
if c == '[':
stack.append([res, multi])
res, multi = '', 0
# 若当前字符为],则出栈,并累积计算字符串
# last_res表示中括号外面的字符子串
# cur_multi * res表示中括号里面的字符乘以系数
elif c == ']':
last_res, cur_multi = stack.pop()
res = last_res + cur_multi * res
# 若当前字符为数字,则更新multi(可能是多位数)
elif '0' <= c <= '9':
multi = multi * 10 + int(c)
# 若当前字符是字母,则直接累加进当前子串
else:
res += c
return res
面试题 01.06. 字符串压缩
class Solution:
def compressString(self, S: str) -> str:
if not S:
return ""
ch = S[0]
ans = ''
cnt = 0
for c in S:
# 当前字符c和上一个字符ch相同
if c == ch:
cnt += 1
# 若不同,则后面加上数字cnt,并重置cnt为1
else:
ans += ch + str(cnt)
ch = c
cnt = 1
ans += ch + str(cnt)
return ans if len(ans) < len(S) else S
1047. 删除字符串中的所有相邻重复项【消消乐】
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = list()
for ch in s:
if stack and stack[-1] == ch:
stack.pop()
else:
stack.append(ch)
return "".join(stack)