Every day a leetcode
题目来源:1446. 连续字符
求只包含一种字符的最长非空子字符串的长度。
初始化当前字符连续出现次数 count 为 1。
从 s[1] 开始,向后遍历字符串,如果 s[i]=s[i-1] ,则将count加一,否则将 count 重置为 1。
维护上述过程中 count 的最大值,即为答案。
解法1:遍历
代码:
int max(int a,int b)
{
return a>b?a:b;
}
int maxPower(char * s){
int ans=1;
int count=1;
for(int i=1;i<strlen(s);i++)
{
if(s[i] == s[i-1])
{
count++;
ans=max(ans,count);
}
else count=1;
}
return ans;
}
结果:

本文介绍了一种动态规划的方法来解决寻找字符串中只包含一种字符的最长非空子字符串的问题。通过遍历字符串并维护当前字符连续出现的计数,可以找到最大计数值,从而得到答案。代码示例展示了该算法的实现。
311

被折叠的 条评论
为什么被折叠?



