要求
给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。
请你返回字符串的能量。
示例 1:
输入:s = "leetcode"
输出:2
解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。
示例 2:
输入:s = "abbcccddddeeeeedcba"
输出:5
解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。
示例 3:
输入:s = "triplepillooooow"
输出:5
示例 4:
输入:s = "hooraaaaaaaaaaay"
输出:11
示例 5:
输入:s = "tourist"
输出:1
提示:
- 1 <= s.length <= 500
- s 只包含小写英文字母。
要求
class Solution:
def maxPower(self, s: str) -> int:
res = 1
pre = s[0]
tmp = 1
for i,ch in enumerate(s):
if i:
if ch == pre:
tmp += 1
else:
pre = ch
tmp = 1
res = max(res,tmp)
return res
解题思路:线性扫描数组,用变量pre记录前一个字符, 用变量tmp记录以当前字符为结尾的只包含一种字符的最长非空子字符串的长度。时间复杂度:O(N)空间复杂度:O(1)