394. 字符串解码

问题链接

https://leetcode.cn/problems/decode-string/description/

解题思路

这题一看就是个典型的递归题目,典型的递归函数的定义就是递归函数的解。

我们首先定义递归函数的参数和返回值。

递归函数的参数显然就是一个字符串,递归函数的返回值是经过计算的字符串。

我们按照递归的一般思路对这个题目进行分析。

我们看看本层需要处理什么。

这个题目,有缩小规模潜质的字符串,显然是上一层中某个被包裹在中括号中的片段。

也就是说,我们如果用一个下标来计数,我们可能在本层的字符串中遇到数字(不一定是个位数) 也有可能遇到边界符号,也有可能遇到正常的英文字符。

三者出现的顺序也有讲究,数字绝对会出现在边界符号之前,并且紧挨着。

如果是遇到数字的话,那可以先把数字提取出来,然后将其之后的有缩小规模潜质的字符串交给下一层递归进行运算。

最后我们看递归的退出条件。

当遍历完本层之后,自然退出即可。

代码

class Solution:
    def decodeString(self, s: str) -> str:
        idx, length = 0, len(s)
        res = ''
        while idx < length:
            if self.is_num(s[idx]):
                n_left, n_right = idx, self.get_num_right_idx(s, idx)
                num = self.st2i(s[n_left: n_right+1])
                nxt_left_idx = n_right + 1
                nxt_right_idx = self.get_right_idx(s, nxt_left_idx)
                res += num * self.decodeString(s[nxt_left_idx+1: nxt_right_idx])
                idx = nxt_right_idx + 1
            else:
                res += s[idx]
                idx += 1
        return res

    def is_num(self, n):
        if n in '0123456789':
            return True
        return False

    def st2i(self, n):
        return int(n)

    def get_num_right_idx(self, n, left_idx):
        for i in range(left_idx, len(n)):
            if not self.is_num(n[i]):
                return i-1
    def get_right_idx(self, n, left_idx):
        cnt = 0
        for i in range(left_idx, len(n)):
            if n[i] == '[':
                cnt += 1
            if n[i] == ']':
                cnt -= 1
            if cnt == 0:
                return i

 

posted @ 2023-01-10 00:24  BJFU-VTH  阅读(29)  评论(0编辑  收藏  举报