Leetcode-394题:Decode String

Given an encoded string, return it's decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

代码:

class Solution(object):
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        stack = []
        i = 0
        while i < len(s):
            if s[i] == ']':
                ll = []
                t = stack.pop()
                while True:
                    if t.isdigit():
                        stack.append(''.join(ll * int(t)))
                        break
                    elif t == '[':
                        pass
                    else:
                        ll.insert(0, t)
                    t = stack.pop()
            elif s[i].isdigit():
                ll = []
                while s[i].isdigit():
                    ll.append(s[i])
                    i += 1
                stack.append(''.join(ll))
                continue
            else:
                stack.append(s[i])
            i += 1
        return ''.join(stack)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,428评论 3 20
  • 007很流行的一句话 截止日期是第一生产力 我觉得说的特别贴切。 生产力,百度百科的解释是,人类创造新财富的能力。...
    飘飘轻阅读 6,682评论 0 8
  • 曾经自己是个做事没有计划,效率的人。总是因为各种紧急且重要的事,因为没有养成良好的习惯,没有在事情重要且不紧...
    华珍卓越觉醒阅读 356评论 2 1
  • 时间把海水熬成了沉闷的风暴。 一触即发的如同兵临城下的战争。 你渴求的无风无浪的宁静早晨也许只是凭记忆勾勒的画。 ...
    吕旅阅读 276评论 0 0