LeetCode 题解工作台
最长的字母序连续子字符串的长度
字母序连续字符串 是由字母表中连续字母组成的字符串。换句话说,字符串 "abcdefghijklmnopqrstuvwxyz" 的任意子字符串都是 字母序连续字符串 。 例如, "abc" 是一个字母序连续字符串,而 "acb" 和 "za" 不是。 给你一个仅由小写英文字母组成的字符串 s ,返回…
1
题型
7
代码语言
3
相关题
当前训练重点
中等 · String-driven solution strategy
答案摘要
我们可以遍历字符串 ,用一个变量 记录最长的字母序连续子字符串的长度,用另一个变量 记录当前连续子字符串的长度。初始时 $\textit{ans} = \textit{cnt} = 1$。 接下来,我们从下标为 的字符开始遍历字符串 ,对于每个字符 ,如果 $s[i] - s[i - 1] = 1$,则说明当前字符和前一个字符是连续的,此时 $\textit{cnt} = \textit{c…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
字母序连续字符串 是由字母表中连续字母组成的字符串。换句话说,字符串 "abcdefghijklmnopqrstuvwxyz" 的任意子字符串都是 字母序连续字符串 。
- 例如,
"abc"是一个字母序连续字符串,而"acb"和"za"不是。
给你一个仅由小写英文字母组成的字符串 s ,返回其 最长 的 字母序连续子字符串 的长度。
示例 1:
输入:s = "abacaba" 输出:2 解释:共有 4 个不同的字母序连续子字符串 "a"、"b"、"c" 和 "ab" 。 "ab" 是最长的字母序连续子字符串。
示例 2:
输入:s = "abcde" 输出:5 解释:"abcde" 是最长的字母序连续子字符串。
提示:
1 <= s.length <= 105s由小写英文字母组成
解题思路
方法一:一次遍历
我们可以遍历字符串 ,用一个变量 记录最长的字母序连续子字符串的长度,用另一个变量 记录当前连续子字符串的长度。初始时 。
接下来,我们从下标为 的字符开始遍历字符串 ,对于每个字符 ,如果 ,则说明当前字符和前一个字符是连续的,此时 ,并更新 ;否则,说明当前字符和前一个字符不连续,此时 。
最终返回 即可。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def longestContinuousSubstring(self, s: str) -> int:
ans = cnt = 1
for x, y in pairwise(map(ord, s)):
if y - x == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to track the longest substring efficiently
- question_mark
Effective use of variables to maintain substring length
- question_mark
Clear understanding of edge cases and constraints
常见陷阱
外企场景- error
Overcomplicating the problem with unnecessary nested loops
- error
Not properly handling edge cases such as strings of length one or no alphabetical sequences
- error
Failure to update the longest substring correctly during iteration
进阶变体
外企场景- arrow_right_alt
Consider different ways to scan through the string, such as using sliding window techniques
- arrow_right_alt
Extend the problem to handle uppercase letters as well
- arrow_right_alt
Modify the problem to return the actual substring instead of just its length