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

核心是理解题意,总结规律,属于哪一类题目。 此题的规律在于 嵌套组合(数字+字母), 而且从dp的角度看,每消除一个底层【】,就会形成一个新的底层【】。

所以规律是 解决 最里侧的【】。如此往复。

完成从内往外层层解决【】,需要保持字符串的记忆。stack可以完成。 再加上列表操作和字符串追加的小技巧。

应用:栈的操作,保持一个字符串的状态,并可以从后往前进行处理。

记忆时间的先后顺序, stack可以完成。 动态规划也可以。

思考问题可以从前往后考虑解决办法,也可以从后往前考虑,如果不能线性找到解决整体的办法,就采用动态规划的思想,找到解决局部问题的方法。

正则解法:
import re
class Solution:
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        pattern=re.compile('(\d+)\[([a-zA-Z]+)\]')
        while '[' in s:
            result_tmp=pattern.search(s)
            print(result_tmp.groups())
            # if result_tmp:
            #     for freq,dst in result_tmp.group():
            freq,dst = result_tmp.groups()
            dst_str=dst*int(freq)
            # print(dst)
            s=pattern.sub(dst_str,s)
            # print(dst,s)
        return s
if __name__=='__main__':
    s = "3[a]2[bc]"
    s = "3[a2[c]]"
    s='3[a]2[bc]'
    s='3[a]2[b4[F]c]'
    s="2[ab3[cd]]4[xy]"
    st=Solution()
    out=st.decodeString(s)
    print(out)
栈队列解法:
class Solution:
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        stack=[[1,'']]
        final_str=''
        num=''
        for char_iter in s:
            if char_iter.isdigit():
                num+=char_iter
                # stack.append([char_iter,''])
            elif char_iter=='[':
                stack.append([int(num),''])
                num=''
            elif char_iter.isalpha():
                stack[-1][-1]+=char_iter
            elif char_iter==']':
                # print(stack)
                freq_chars=stack.pop()
                # print(freq_chars)
                str_tmp=freq_chars[1]*int(freq_chars[0])
                stack[-1][-1]+=str_tmp
            else:
                stack[0][-1]+=str_tmp
        # print(final_str)
        # print(stack)
        return stack[0][1]


if __name__=='__main__':
    s = "3[a]2[bc]"
    s = "3[a2[c]]"
    s='3[a]2[bc]'
    s='3[a]2[b4[F]c]'
    s="2[ab3[cd]]4[xy]"
    s='"2[abc]3[cd]ef"'
    s="100[leetcode]"
    st=Solution()
    out=st.decodeString(s)
    print(out)
    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000016191114
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞