394. Decode String题解(堆栈法)

题目链接https://leetcode.com/problems/decode-string/

题解:

在discussion看到不少堆栈解法,虽然很巧妙,但是不自己走一下流程,容易忽略一些细节,题目记得也不深刻。用堆栈法:首先接收数字,遇到'[',把数字和‘’推入栈中,将数字变量置为空,以便接收嵌套的数字;依次读入字母,与第二个元素连接,遇到']',将栈推出,保存到最终的res变量。需要注意无'[]'的字母,直接保存到res即可。

代码:

class Solution(object):
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        res = ''
        num = ''
        stack = []
        for ch in s:
            if ch.isdigit():
                num += ch
            elif ch == '[':
                stack.append([int(num), ''])
                num = ''
            elif ch.isalpha():
                if len(stack) == 0:
                    res += ch
                else:
                    stack[-1][1] += ch
            elif ch == ']':
                k, str_tmp = stack.pop()
                if len(stack) != 0:
                    stack[-1][1] += k*str_tmp
                else:
                    res += k*str_tmp
        return res

猜你喜欢

转载自blog.csdn.net/scut_salmon/article/details/89222865
今日推荐