LeetCode 题解工作台

连续字符

给你一个字符串 s ,字符串的 「能量」 定义为:只包含一种字符的最长非空子字符串的长度。 请你返回字符串 s 的 能量 。 示例 1: 输入: s = "leetcode" 输出: 2 解释: 子字符串 "ee" 长度为 2 ,只包含字符 'e' 。 示例 2: 输入: s = "abbcccdd…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们定义一个变量 ,表示当前连续字符的长度,初始时 。 接下来,我们从字符串 的第二个字符开始遍历,如果当前字符与上一个字符相同,那么 $\textit{t} = \textit{t} + 1$,然后更新答案 $\textit{ans} = \max(\textit{ans}, \textit{t})$;否则 $\textit{t} = 1$。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。

请你返回字符串 s能量

 

示例 1:

输入:s = "leetcode"
输出:2
解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。

示例 2:

输入:s = "abbcccddddeeeeedcba"
输出:5
解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。

 

提示:

  • 1 <= s.length <= 500
  • s 只包含小写英文字母。
lightbulb

解题思路

方法一:遍历计数

我们定义一个变量 t\textit{t},表示当前连续字符的长度,初始时 t=1\textit{t}=1

接下来,我们从字符串 ss 的第二个字符开始遍历,如果当前字符与上一个字符相同,那么 t=t+1\textit{t} = \textit{t} + 1,然后更新答案 ans=max(ans,t)\textit{ans} = \max(\textit{ans}, \textit{t});否则 t=1\textit{t} = 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 maxPower(self, s: str) -> int:
        ans = t = 1
        for a, b in pairwise(s):
            if a == b:
                t += 1
                ans = max(ans, t)
            else:
                t = 1
        return ans
speed

复杂度分析

指标
时间O(N)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Ability to identify patterns in consecutive strings.

  • question_mark

    Efficient use of space while solving string problems.

  • question_mark

    Correct understanding of linear time complexity for string manipulation.

warning

常见陷阱

外企场景
  • error

    Not updating the maximum length correctly after encountering different characters.

  • error

    Mismanaging the substring length when the character count resets.

  • error

    Overcomplicating the problem with unnecessary data structures.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the string contains no repeated characters? This would still work, as each character would be a substring of length 1.

  • arrow_right_alt

    What if the string is made up of the same character throughout? The maximum power would be the length of the entire string.

  • arrow_right_alt

    How would the solution change if the string was very long? The current solution remains optimal with O(N) time complexity.

help

常见问题

外企场景

连续字符题解:String-driven solution … | LeetCode #1446 简单