Python 解LeetCode:394 Decode String

  • 题目描述:按照规定,把字符串解码,具体示例见题目链接

  • 思路:使用两个栈分别存储数字和字母

  • 注意1: 数字是多位的话,要处理后入数字栈

  • 注意2: 出栈时过程中产生的组合后的字符串要继续入字母栈

  • 注意3: 记得字母出栈的时候字符要逆序组合成字符串

  • 注意4: 不用字符串而用字母栈的原因是字符串的 join 效率会比字符串加法高一些

  • 结果: 30 ms, beat 98.02%

  • 缺点:判断是数字那里有点代码不简洁,可以把 j 挪到循环外面的

class Solution(object):
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        nums, chars = [], []
        i, length = 0, len(s)
        while i < length:
            j = i + 1
            if s[i].isdigit():
                num = int(s[i])
                while j < length:
                    if s[j].isdigit():
                        num = num * 10 + int(s[j])
                        j += 1
                    else:
                        break
                nums.append(num)
            elif s[i] == '[' or s[i].isalpha():
                chars.append(s[i])
            else:
                t, tmpc = chars.pop(), []
                while t != '[':
                    tmpc.append(t)
                    t = chars.pop()
                tchars = nums.pop() * ''.join(tmpc[::-1])
                chars.append(tchars)
            i = j
        return ''.join(chars)
posted @ 2018-05-16 22:55  潇湘旧友  阅读(1354)  评论(0编辑  收藏  举报