LeetCode 题解工作台

最长的字母序连续子字符串的长度

字母序连续字符串 是由字母表中连续字母组成的字符串。换句话说,字符串 "abcdefghijklmnopqrstuvwxyz" 的任意子字符串都是 字母序连续字符串 。 例如, "abc" 是一个字母序连续字符串,而 "acb" 和 "za" 不是。 给你一个仅由小写英文字母组成的字符串 s ,返回…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · String-driven solution strategy

bolt

答案摘要

我们可以遍历字符串 ,用一个变量 记录最长的字母序连续子字符串的长度,用另一个变量 记录当前连续子字符串的长度。初始时 $\textit{ans} = \textit{cnt} = 1$。 接下来,我们从下标为 的字符开始遍历字符串 ,对于每个字符 ,如果 $s[i] - s[i - 1] = 1$,则说明当前字符和前一个字符是连续的,此时 $\textit{cnt} = \textit{c…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

字母序连续字符串 是由字母表中连续字母组成的字符串。换句话说,字符串 "abcdefghijklmnopqrstuvwxyz" 的任意子字符串都是 字母序连续字符串

  • 例如,"abc" 是一个字母序连续字符串,而 "acb""za" 不是。

给你一个仅由小写英文字母组成的字符串 s ,返回其 最长 的 字母序连续子字符串 的长度。

 

示例 1:

输入:s = "abacaba"
输出:2
解释:共有 4 个不同的字母序连续子字符串 "a"、"b"、"c" 和 "ab" 。
"ab" 是最长的字母序连续子字符串。

示例 2:

输入:s = "abcde"
输出:5
解释:"abcde" 是最长的字母序连续子字符串。

 

提示:

  • 1 <= s.length <= 105
  • s 由小写英文字母组成
lightbulb

解题思路

方法一:一次遍历

我们可以遍历字符串 ss,用一个变量 ans\textit{ans} 记录最长的字母序连续子字符串的长度,用另一个变量 cnt\textit{cnt} 记录当前连续子字符串的长度。初始时 ans=cnt=1\textit{ans} = \textit{cnt} = 1

接下来,我们从下标为 11 的字符开始遍历字符串 ss,对于每个字符 s[i]s[i],如果 s[i]s[i1]=1s[i] - s[i - 1] = 1,则说明当前字符和前一个字符是连续的,此时 cnt=cnt+1\textit{cnt} = \textit{cnt} + 1,并更新 ans=max(ans,cnt)\textit{ans} = \max(\textit{ans}, \textit{cnt});否则,说明当前字符和前一个字符不连续,此时 cnt=1\textit{cnt} = 1

最终返回 ans\textit{ans} 即可。

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

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

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

面试官常问的追问

外企场景
  • 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

warning

常见陷阱

外企场景
  • 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

swap_horiz

进阶变体

外企场景
  • 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

help

常见问题

外企场景

最长的字母序连续子字符串的长度题解:String-driven solution … | LeetCode #2414 中等