试写一个函数,计算字符串s中最大连续相同的字符个数。例如,若s为“aaabbbb”,则返回值为4:若s为“abcde”,则返回为1。
#include<stdio.h>
#include <string.h>
int max_consecutive_chars(const char *s) {
if (!s || !strlen(s)) return 0;
int max_count = 1;
int current_count = 1;
for (int i = 1; s[i] != '\0'; ++i) {
if (s[i] == s[i - 1]) {
++current_count;
} else {
max_count = (current_count > max_count) ? current_count : max_count;
current_count = 1;
}
}
// 检查最后一个字符的连续计数是否大于当前最大计数
max_count = (current_count > max_count) ? current_count : max_count;
return max_count;
}
int main() {
char s1[] = "aaabbbb";
char s2[] = "abcde";
printf("Max consecutive chars in '%s': %d\n", s1,max_consecutive_chars(s1));
printf("Max consecutive chars in '%s': %d\n", s2,max_consecutive_chars(s2));
return 0;
}