码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-24 01:50:54      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:style   blog   os   io   ar   2014   log   amp   size   

题目完整描述为:用递归的方式实现一个求字符串中连续出现相同字符的最大值,如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++;
    int tmp = Get(t);
    return ans > tmp ? ans : tmp;
}

int main()
{
    printf("%d\n", Get("abbc"));
    printf("%d\n", Get("aaabbcc"));

    getchar();
    return 0;
}
不知道为什么一定要是递归实现。。。可能是要考察写递归的能力吧,无所谓,反正笔试面试题都很怪异就是了-.-

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

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

标签:style   blog   os   io   ar   2014   log   amp   size   

原文地址:http://blog.csdn.net/hactrox/article/details/38788355

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!