decode string

394. Decode String

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
 1 class Solution(object):
 2     def decodeString(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7 
 8         stack=[]
 9         curNum=0
10         curStr=''
11 
12         for ch in s:
13             if ch=='[':
14                 stack.append(curStr)
15                 stack.append(curNum)
16                 curStr=""
17                 curNum=0
18             elif ch==']':
19                 num=stack.pop()
20                 preStr=stack.pop()
21                 curStr=preStr+num*curStr
22             elif ch.isdigit():
23                 curNum=curNum*10+int(ch)
24             else:
25                 curStr+=ch
26 
27         return curStr

 

posted @ 2020-03-22 11:23  7aughing  阅读(210)  评论(0编辑  收藏  举报