微软算法面试(18):字符串中找最长数字字符串
题目:在字符串中找出连续最长字符串,并把这个串的长度返回。
例如:字符串“abcd12345ed125ss123456789”,他的最长字符串为“123456789“,长度为9.
实现如下:
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int continumax(char *outputstr,char *intputstr)
{
int maxint = 0;
int i = 0;
int j = -1;
int i1 = -1;
int j1 = -1;
while( i < strlen(intputstr))
{
if(intputstr[i] >= '0' && intputstr[i] <= '9')//Êý×Ö
{
if(j == -1)
j = i;
}
else
{
if(j != -1)
{
if(maxint < (i - j))
{
i1 = i;
j1 = j;
maxint = i - j;
}
j = -1;
}
}
i ++;
}
if(intputstr[i-1] >= '0' && intputstr[i-1] <= '9')
{
if(maxint < (i - j))
{
i1 = i;
j1 = j;
maxint = i - j;
}
}
strncpy(outputstr, intputstr + j1, maxint);
return maxint;
}
int main()
{
char a[100] = "abcd12345ed125ss123456789";
char b[100];
int maxlen = continumax(b, a);
cout << a << " max sub integerstring is: " << b << " len: " << maxlen << endl;
return 0;
}
输出结果为:
abcd12345ed125ss123456789 max sub integerstring is: 123456789 len: 9