LeetCode 题解工作台

索引处的解码字符串

给定一个编码字符串 s 。请你找出 解码字符串 并将其写入磁带。解码时,从编码字符串中 每次读取一个字符 ,并采取以下步骤: 如果所读的字符是字母,则将该字母写在磁带上。 如果所读的字符是数字(例如 d ),则整个当前磁带总共会被重复写 d-1 次。 现在,对于给定的编码字符串 s 和索引 k ,查…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 栈·状态

bolt

答案摘要

我们可以先计算出解码字符串的总长度 ,然后从后向前遍历字符串,每次更新 为 $k \bmod m$,直到 为 且当前字符为字母,返回当前字符。否则,如果当前字符为数字,则将 除以该数字。如果当前字符为字母,则将 减 。 时间复杂度 ,其中 为字符串的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个编码字符串 s 。请你找出 解码字符串 并将其写入磁带。解码时,从编码字符串中 每次读取一个字符 ,并采取以下步骤:

  • 如果所读的字符是字母,则将该字母写在磁带上。
  • 如果所读的字符是数字(例如 d),则整个当前磁带总共会被重复写 d-1 次。

现在,对于给定的编码字符串 s 和索引 k,查找并返回解码字符串中的第 k 个字母。

 

示例 1:

输入:s = "leet2code3", k = 10
输出:"o"
解释:
解码后的字符串为 "leetleetcodeleetleetcodeleetleetcode"。
字符串中的第 10 个字母是 "o"。

示例 2:

输入:s = "ha22", k = 5
输出:"h"
解释:
解码后的字符串为 "hahahaha"。第 5 个字母是 "h"。

示例 3:

输入:s = "a2345678999999999999999", k = 1
输出:"a"
解释:
解码后的字符串为 "a" 重复 8301530446056247680 次。第 1 个字母是 "a"。

 

提示:

  • 2 <= s.length <= 100
  • s 只包含小写字母与数字 29
  • s 以字母开头。
  • 1 <= k <= 109
  • 题目保证 k 小于或等于解码字符串的长度。
  • 解码后的字符串保证少于 263 个字母。
lightbulb

解题思路

方法一:逆向思维

我们可以先计算出解码字符串的总长度 mm,然后从后向前遍历字符串,每次更新 kkkmodmk \bmod m,直到 kk00 且当前字符为字母,返回当前字符。否则,如果当前字符为数字,则将 mm 除以该数字。如果当前字符为字母,则将 mm11

时间复杂度 O(n)O(n),其中 nn 为字符串的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
    def decodeAtIndex(self, s: str, k: int) -> str:
        m = 0
        for c in s:
            if c.isdigit():
                m *= int(c)
            else:
                m += 1
        for c in s[::-1]:
            k %= m
            if k == 0 and c.isalpha():
                return c
            if c.isdigit():
                m //= int(c)
            else:
                m -= 1
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for understanding of stack-based state management.

  • question_mark

    Evaluate how the candidate optimizes space and avoids full string expansion.

  • question_mark

    Assess the candidate's ability to work with large numbers and memory constraints.

warning

常见陷阱

外企场景
  • error

    Mistaking the problem as requiring full string expansion, which leads to inefficient memory use.

  • error

    Not properly managing stack state and traversal, resulting in incorrect indexing or performance issues.

  • error

    Overcomplicating the problem and missing the straightforward stack-based solution.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling very large k values efficiently without running out of memory.

  • arrow_right_alt

    Modifying the approach to handle different patterns of repetition beyond digits 2-9.

  • arrow_right_alt

    Adapting the method to return substrings instead of single characters.

help

常见问题

外企场景

索引处的解码字符串题解:栈·状态 | LeetCode #880 中等