给你一个字符串 s
,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。
请你返回字符串 s
的 能量。
示例 1:
输入:s = "leetcode" 输出:2 解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。
示例 2:
输入:s = "abbcccddddeeeeedcba" 输出:5 解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。
代码如下:
class Solution {
public:
int maxPower(string s) {
int sum=1;//存放最大值
int count=1;//记录每次字符一样的个数
for(int i=1;i<s.size();i++)
{
if(s[i]==s[i-1])//当两个字符一样时
{
count++;//count+1
sum=max(sum,count);//每次都保存最大的个数
}
else
{
count=1;//如果相邻的两个字符不相等,让count==1
}
}
return sum;//最终返回最大值
}
};