[leetcode/lintcode 題解] Google面試題:字串解碼
阿新 • • 發佈:2020-10-28
給出一個表示式 s,此表示式包括數字,字母以及方括號。在方括號前的數字表示方括號內容的重複次數(括號內的內容可以是字串或另一個表示式),請將這個表示式展開成一個字串。
線上評測地址:領釦題庫官網
樣例1
輸入: S = abc3[a]
輸出: "abcaaa"
樣例2
輸入: S = 3[2[ad]3[pf]]xyz
輸出: "adadpfpfpfadadpfpfpfadadpfpfpfxyz"
題解
把所有字元一個個放到 stack 裡, 如果碰到了 ],就從 stack 找到對應的字串和重複次數,decode 之後再放回 stack 裡。
class Solution:
"""
"""
def expressionExpand(self, s):
stack = []
for c in s:
if c != ']':
stack.append(c)
continue
strs = []
while stack and stack[-1] != '[':
strs.append(stack.pop ())
# skip '['
stack.pop()
repeats = 0
base = 1
while stack and stack[-1].isdigit():
repeats += (ord(stack.pop()) - ord('0')) * base
base *= 10
stack.append(''.join(reversed(strs)) * repeats)
return ''.join(stack)
更多題解參考:九章官網solution