[2013百度软件研发笔试题] 求字符串中连续出现相同字符的最大值

来源:互联网 发布:主播 真人 素颜 知乎 编辑:程序博客网 时间:2024/05/21 02:19

题目完整描述为:用递归的方式实现一个求字符串中连续出现相同字符的最大值,如aaabbcc,连续出现a的最大值为3,abbc,连续出现字符最大的值为2。


以下是我想出来的方法:

#include <iostream>using namespace std;#define MAX(a, b) (a) > (b) ? (a) : (b)int Get(char *s, int n, int m)  //字符指针, 当前最长串, max最长串{    if(*(s+1) == '\0')        return MAX(n, m);    if(*s == *(s+1))        return Get(s+1, n+1, m);    return Get(s+1, 1, MAX(n, m));}int main(){    printf("%d\n", Get("abbc", 1, 1));     printf("%d\n", Get("aaabbcc", 1, 1));     getchar();    return 0;}

以及另一种递归的方法:

#include <iostream>using namespace std;int Get(char *s){    int ans = 0;    char *t = s;    if(*s == '\0')        return ans;    while(*s != '\0' && *t == *s)        ans++, s++;    t = s;    int tmp = Get(t);    return ans > tmp ? ans : tmp;}int main(){    printf("%d\n", Get("abbc"));    printf("%d\n", Get("aaabbcc"));    getchar();    return 0;}
不知道为什么一定要是递归实现。。。可能是要考察写递归的能力吧,无所谓,反正笔试面试题都很怪异就是了-.-

如果你有其他更好的方法,请赐教!

18 0