1. 程式人生 > >LeetCode394:Decode String

LeetCode394: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".

LeetCode:連結

看到括號匹配的題肯定想到用棧去做。

這個題,遇到’[‘就把之前的字串進行進棧操作。遇到’]'進行出棧操作curstring儲存的是出棧操作完成後的字串。注意這一步:curstring = prestring + prenum * curstring,prestring是前面的字串,prenum * curstring是這一步驟結束之後的字串,所以是前面的字串+現在的字串得到目前已有的字串

class Solution(object):
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        stack = []
        curstring = ''
        curnum = 0
        for char in s:
            if char == '[':
                stack.append(curstring)
                stack.append(curnum)
                # 之前的進棧之後就重頭開始
                curstring = ''
                curnum = 0
            elif char == ']':
                prenum = stack.pop()
                prestring = stack.pop()
                curstring = prestring + curstring * prenum
            elif char.isdigit():
                # 如果是"100[leetcode]" 就必須用10 * curnum + int(char)
                curnum = 10 * curnum + int(char)
            else:
                curstring += char
        return curstring