原題
給一段string银锻,解碼
樣例
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
解題思路
- 一個(gè)stack記錄倍數(shù)
- 一個(gè)stack記錄string
- 遇到"["添加倍數(shù)(因?yàn)楸稊?shù)可能是“123”...), 遇到"]"彈出一段string乘以倍數(shù),再壓入棧
完整代碼
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
if not s:
return ""
digit = []
string = []
temp_digit = ""
for char in s:
if char.isdigit():
temp_digit += char
elif char == "[":
digit.append(int(temp_digit))
string.append(char)
temp_digit = ""
elif char == "]":
cur = []
temp = string.pop()
while string and temp != "[":
cur.insert(0, temp)
temp = string.pop()
for i in range(digit.pop()):
string += cur
else:
string.append(char)
return "".join(string)