LeetCode 题解工作台
环绕字符串中唯一的子字符串
定义字符串 base 为一个 "abcdefghijklmnopqrstuvwxyz" 无限环绕的字符串,所以 base 看起来是这样的: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...." . 给你一个字符串 s ,…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们不妨定义一个长度为 的数组 ,其中 表示以第 个字符结尾的最长连续子串的长度。那么答案就是 中所有元素的和。 我们定义一个变量 ,表示以当前字符结尾的最长连续子串的长度。遍历字符串 ,对于每个字符 ,如果 和前一个字符 $s[i - 1]$ 之间的差值为 ,那么 就加 ,否则 重置为 。然后更新 为 和 的较大值。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
定义字符串 base 为一个 "abcdefghijklmnopqrstuvwxyz" 无限环绕的字符串,所以 base 看起来是这样的:
"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
给你一个字符串 s ,请你统计并返回 s 中有多少 不同非空子串 也在 base 中出现。
示例 1:
输入:s = "a" 输出:1 解释:字符串 s 的子字符串 "a" 在 base 中出现。
示例 2:
输入:s = "cac"
输出:2
解释:字符串 s 有两个子字符串 ("a", "c") 在 base 中出现。
示例 3:
输入:s = "zab"
输出:6
解释:字符串 s 有六个子字符串 ("z", "a", "b", "za", "ab", and "zab") 在 base 中出现。
提示:
1 <= s.length <= 105- s 由小写英文字母组成
解题思路
方法一:动态规划
我们不妨定义一个长度为 的数组 ,其中 表示以第 个字符结尾的最长连续子串的长度。那么答案就是 中所有元素的和。
我们定义一个变量 ,表示以当前字符结尾的最长连续子串的长度。遍历字符串 ,对于每个字符 ,如果 和前一个字符 之间的差值为 ,那么 就加 ,否则 重置为 。然后更新 为 和 的较大值。
最后返回 中所有元素的和即可。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 ,其中 是字符集,这里是小写字母集合。
class Solution:
def findSubstringInWraproundString(self, s: str) -> int:
f = defaultdict(int)
k = 0
for i, c in enumerate(s):
if i and (ord(c) - ord(s[i - 1])) % 26 == 1:
k += 1
else:
k = 1
f[c] = max(f[c], k)
return sum(f.values())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates understanding of dynamic programming and efficient state transitions.
- question_mark
Candidate suggests using a fixed-size array for the 26 alphabet characters, optimizing space complexity.
- question_mark
Candidate avoids brute-force solutions and is aware of the time constraints, emphasizing efficiency.
常见陷阱
外企场景- error
Not utilizing dynamic programming to track longest substrings, leading to inefficient solutions.
- error
Mismanaging the `dp` array, causing incorrect substring length updates.
- error
Failing to consider the circular nature of the wraparound string, which may lead to overlooked substring connections.
进阶变体
外企场景- arrow_right_alt
Modifying the base string to be a different cyclic sequence, such as '0123456789'.
- arrow_right_alt
Considering uppercase English letters in the string `s`.
- arrow_right_alt
Allowing for multiple string queries, where each query involves calculating the unique substrings for a different string `s`.