在字符串中找出连续最长的数字串

函数原型: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值