一.题目:
字符串解码.
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
二.解题思路:
这种题类似于计算器计算题型.我们通常在解题时需要设计两个栈来储存数字和字母.需要注意的点:
(1)数字可能是多位的;
(2)遇到"]“时将字母栈中上一个”["之后的字母要全部排出来,然后数字栈排出一个元素得到新的字符串再放入到字母栈中;
代码如下:
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
nums,char = [],[]
i = 0
length = len(s)
while i < length:
if s[i].isdigit():
num = 0
while i<length and s[i].isdigit():
num = 10*num + int(s[i])
i +=1
nums.append(num)
elif s[i] == "[" or s[i].isalpha():
char.append(s[i])
i +=1
else:
char1 = char.pop()
tmp = []
while char1 != "[":
tmp.append(char1)
char1 = char.pop()
num = nums.pop()
new_char = num * "".join(tmp[::-1])
char.append(new_char)
i +=1
return "".join(char)