题目:
思路:
我首先想到的就是用字典来记录不同字符的最长个数,关于当前连续字符的个数,用了一个count来计数,如果一样则count加一,一旦有不一样,则进入判断,主要是判断当前key是否在列表中,如果不在直接添加,在的话要判断当前记录的连续字符的个数和字典中的值哪个大,如果当前连续个数大则更新value,当前小则不做任何处理。
注意不要忽略了最后一个字符的统计,因为最后一个字符会因为循环的原因没记录到就跳出循环,所以在循环外也要再判断一次。
代码:
class Solution:
def maxPower(self, s: str) -> int:
dict = {}
key = s[0]
i = 0
count = 0
while i < len(s):
if key == s[i]: # 如果两个连续一样的
count+=1
else: # 如果有不一样的了
if key in dict:
if dict[key] < count:
dict[key] = count
else:
dict[key] = count
key = s[i]
count = 1
i += 1
if key in dict:
if dict[key] < count:
dict[key] = count
else:
dict[key] = count
return max(dict.values())
结果:
关于LeetCode的解题方法欢迎大家一起讨论~