LeetCode 题解工作台
连续字符
给你一个字符串 s ,字符串的 「能量」 定义为:只包含一种字符的最长非空子字符串的长度。 请你返回字符串 s 的 能量 。 示例 1: 输入: s = "leetcode" 输出: 2 解释: 子字符串 "ee" 长度为 2 ,只包含字符 'e' 。 示例 2: 输入: s = "abbcccdd…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们定义一个变量 ,表示当前连续字符的长度,初始时 。 接下来,我们从字符串 的第二个字符开始遍历,如果当前字符与上一个字符相同,那么 $\textit{t} = \textit{t} + 1$,然后更新答案 $\textit{ans} = \max(\textit{ans}, \textit{t})$;否则 $\textit{t} = 1$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。
请你返回字符串 s 的 能量。
示例 1:
输入:s = "leetcode" 输出:2 解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。
示例 2:
输入:s = "abbcccddddeeeeedcba" 输出:5 解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。
提示:
1 <= s.length <= 500s只包含小写英文字母。
解题思路
方法一:遍历计数
我们定义一个变量 ,表示当前连续字符的长度,初始时 。
接下来,我们从字符串 的第二个字符开始遍历,如果当前字符与上一个字符相同,那么 ,然后更新答案 ;否则 。
最后返回答案 即可。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.