字符串操作系列_1在字符串中找出连续最长的数字串

来源:互联网 发布:windows更新组策略 编辑:程序博客网 时间:2024/05/22 12:07

        字符串操作在各大小公司的笔试和面试中经常出现,“字符串操作系列”的目标是整理出常见的字符串操作题目,并给出笔者的参考代码。笔者将不断更新该系列博文,敬请关注!

题目:写一个函数,它的原形是int continumax(char *outputstr,char *intputstr)

功能:在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串付给其中一个函数参数outputstr所指内存。

例如:"abcd12345ed125ss123456789"的首地址传给intputstr后,函数将返回9,outputstr所指的值为123456789

分析:设输入的字符串长度为n,分配一个大小为n的整型数组count,count[i]记录了原字符串中第i个字符之前的最大连续数字串长度。则count[i]具有如下递推关系:

       count[i] = count[i-1]+1,当第i个字符为数字,

       count[i] = 0,当第i个字符非数字。

好了,下面贴出c/c++源代码:

#include <iostream>#include<assert.h>using namespace std;int continumax(char *outputstr,char *intputstr){assert(NULL!=outputstr && NULL!=intputstr);int len = strlen(intputstr);int *count = new int[len];int max = 0;char* p = intputstr;for(int i=0; i<len; i++){count[i] = 0;if(*(p+i)>='0' && *(p+i)<='9'){if(0==i){count[i] = 1;}else{count[i] = count[i-1]+1;}if(count[i]>count[max]){max = i;}}}char* t = p+max-count[max]+1;for(int i=0;i<count[max];i++){*outputstr++ = *(t+i);}*outputstr = '\0';max = count[max];//注意释放内存,防止内存泄漏delete []count;return max;}int main(){char* str = "abcd12345ed125ss123456789";char* digitStr = new char[strlen(str)+1];cout<<continumax(digitStr,str)<<endl;cout<<str<<endl;cout<<digitStr<<endl;return 0;}

源代码运行结果如下:


原创粉丝点击