统计输入的字符串中最大连续重复字母的个数,比如adsfdasefe,里面没有连续重复的,为0。aabbbsdsff,最大连续重复个数为3…听说该题有巧妙算法…
int numberOfContinuousAlphas(char *str){
int i=0,tmp = 1,count= 0;
while (str[i]) {
if (str[i] == str[i+1]) {
tmp ++;
if (tmp > count&&tmp>=2) {
count = tmp;
}
}else tmp = 1;
i++;
}
return count;
}
考虑因素:
考虑到某个字符出现后,个数必然至少为1,但是如果不出现重复,那么重复次数为0;一旦连续出现2个或者以上,那么应当返回该字符的个数。当然这个规定可以自行设定。
当且仅当某次某个字符个数tmp大于原先存储的count最大值,且该字符的确重复出现(也就是tmp》=2)时,存储新值。当下一个字符和当前字符不同时,设置tmp为1。
改进写法:
int numberOfContinuousAlphas(char *str){
int i=0,tmp = 1,count= 0;
while (str[i]) {
if (str[i] == str[i+1])
tmp ++;
else{
if (tmp > count&&tmp>=2)
count = tmp;
tmp = 1;
}
i++;
}
return count;
}
上面的代码可以减少count更新次数,相比较原来代码,如果出现长串连续相同字符时,会连续更新count,这是不需要的,只需在字符变化时更新count即可,考虑到字符串以'\0'结束,因此即使是"sdddddd"这样的字符串也会被正确计数。