函数原型:int maxContinue(char *output, const char *input);
比如:abcd12345ed125ss123456789
返回9,output指向"123456789"
复杂度为O(n)
code如下:
#include <iostream>
using namespace std;
const char str[] = "abcd12345ed125ss123456789";
//const char str[] = "abcd12345ed125ss123456789238498154398758 \
9347895173985B734189567314589A34758123758913475981xxc";
//const char str[] = "abc";
bool isdigit(char c)
{
return c >= '0' && c <= '9';
}
bool isalpha(char c)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
char* strncpy(char *dest, const char *source, int n)
{
if(source == NULL && dest == NULL && n <= 0)
return NULL;
while(n) {
n--;
*dest++ = *source++;
}
return dest;
}
int maxContinue(char *&outputStr, const char *inputStr)
{
const char *fast = inputStr, *slow = inputStr;
int len = 0;
const char *start = NULL;
if(inputStr == NULL) {
outputStr = NULL;
return 0;
}
while(*fast != '\0') {
while(*fast != '\0' && (!isdigit(*fast)))
fast++;
slow = fast;
//想想开始写的下面代码为何是错的
//while(*fast != '\0' && (!isalpha(*fast)))
while(*fast != '\0' && (isdigit(*fast)))
fast++;
if(fast - slow > len) {
len = fast - slow;
start = slow;
}
}
//解决全为字符串没有数字串的情形
if(start == NULL) {
outputStr = NULL;
return 0;
}
outputStr = new char[len + 1];
strncpy(outputStr, start, len);
outputStr[len] = 0;
return len;
}
void main()
{
char *output;
int len = maxContinue(output, str);
cout << "len = " << len << endl;
if(output != NULL) {
cout << "output = " << output << endl;
delete[] output;
}
else
cout << "not exist" << endl;
}
测试用例:
1. str为空
char *output, *test = NULL;
int len = maxContinue(output, test);
2. str非空没数字
const char str[] = "abc";
3 str全部为数字,1个或多个
const char str[] = "abcd12345ed125ss123456789";
4. str只含1个数字,且在前、中、尾
const char str[] = "1ab";
const char str[] = "a1b";
const char str[] = "ab1";
5. str包含多个数字串,且在前、中、尾
const char str[] = "123456789012345ab";
const char str[] = "a123456789012345b";
const char str[] = "ab123456789012345";
经测试,上述情况均pass