【问题标题】:Decode String Python3 LeetCode解码字符串 Python3 LeetCode
【发布时间】:2019-11-14 06:13:09
【问题描述】:

大家好!!

我遇到了一个我无法知道问题所在的场景

import re

class Solution:
    def decodeString(self, s):
        find_pat = re.compile(r'(\d+)\[(\w+)\]')
        mo = find_pat.search(s)
        if mo:
            decoded_string = ''
            for i in range(int(mo.group(1))):
                decoded_string += mo.group(2)

            Solution().decodeString(s.replace(mo.group(), decoded_string))
        else:
            return s

我能够在我的终端上获得输出。这是有关该问题的更多上下文

问题: 给定一个编码字符串,返回它的解码字符串。

编码规则是:k[encoded_string],其中方括号内的encoded_string 正好重复k 次。请注意,k 保证为正整数。

你可以假设输入的字符串总是有效的;没有多余的空格,方括号格式正确等。

此外,您可以假设原始数据不包含任何数字,并且数字仅用于那些重复的数字 k。例如,不会有像 3a 或 2[4] 这样的输入。

例子:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

这是我的结果:

谢谢!!

【问题讨论】:

    标签: python-3.x string class return-value regex-group


    【解决方案1】:

    解决办法

    import re
    
    class Solution:
        def decodeString(self, s):
            find_pat = re.compile(r'(\d+)\[(\w+)\]')
    
            while find_pat.search(s):
                mo = find_pat.search(s)
                decoded_string = ''
                for i in range(int(mo.group(1))):
                    decoded_string += mo.group(2)
    
                s = s.replace(mo.group(), decoded_string)
    
            return s
    

    【讨论】:

      猜你喜欢
      • 2021-11-30
      • 2011-08-13
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-18
      相关资源
      最近更新 更多