lintcode练习-575. Decode String

描述

给出一个表达式 s,此表达式包括数字,字母以及方括号。在方括号前的数字表示方括号内容的重复次数(括号内的内容可以是字符串或另一个表达式),请将这个表达式展开成一个字符串。

您在真实的面试中是否遇到过这个题?  是

样例

S = abc3[a] 返回 abcaaa
S = 3[abc] 返回 abcabcabc
S = 4[ac]dy 返回 acacacacdy
S = 3[2[ad]3[pf]]xyz 返回 adadpfpfpfadadpfpfpfadadpfpfpfxyz

挑战

你可以不通过递归的方式完成展开吗?

实现代码:

使用stack

1、当遇到 ‘]’ ,从stack中弹出元素,存入helper数组中,直到 ‘[’为止

2、弹出‘ [’,紧接着就是数字,得到真实的数值multiple

3、对helper重复multiple次,将结果直接加到result上

4、用join将stack展开成字符串

class Solution:
    """
    @param s: an expression includes numbers, letters and brackets
    @return: a string
    """

    def expressionExpand(self, s):
        # write your code here
        result = []
        for item in s:
            if item == ']':
                helper = []
                while result[-1] != '[':
                    helper.append(result.pop())
                result.pop()
                multiple, index = 0, 0
                while result and result[-1].isdigit():
                    multiple += int(result.pop()) * pow(10, index)
                    index += 1
                result += helper[::-1] * multiple
            else:

                result.append(item)

        return ''.join(result)

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81368669