每日一题——在字符串中找出连续最长的数字串

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

在字符串中找出连续最长的数字串
时间限制:3秒
空间限制:32768K

题目描述
请一个在字符串中找出连续最长的数字串,并把这个串的长度返回;如果存在长度相同的连续数字串,返回最后一个连续数字串;
注意:数字串只需要是数字组成的就可以,并不要求顺序,比如数字串“1234”的长度就小于数字串“1359055”,如果没有数字,
则返回空字符串(“”)而不是NULL!(说明:不需要考虑负数)
输入描述 :
字符串输出描述:
连续数字串&在所有数字串最长的长度
示例1
输入
abcd12345ed125ss123058789
输出
123058789
9

源码

/********************************************************************************************

在字符串中找出连续最长的数字串
时间限制:3秒
空间限制:32768K

题目描述
请一个在字符串中找出连续最长的数字串,并把这个串的长度返回;如果存在长度相同的连续数字串,返回最后一个连续数字串;
注意:数字串只需要是数字组成的就可以,并不要求顺序,比如数字串“1234”的长度就小于数字串“1359055”,如果没有数字,
则返回空字符串(“”)而不是NULL!(说明:不需要考虑负数)
输入描述 :
字符串输出描述:
连续数字串&在所有数字串最长的长度
示例1
	输入
	abcd12345ed125ss123058789
	输出
123058789
9
********************************************************************************************/
#include <iostream>
#include <string>
using namespace std;


int main()
{
    
    
	string srt = {
    
     "abcd155555555555552345ed125ss123058789" };
	int len_max = 0;
	int len0 = 0;
	int index = 0;
	for (int i = 0; i < srt.size(); i++)
	{
    
    
		if (srt[i] >= '0'&& srt[i] <= '9')
		{
    
    
			len0++;
			if (len0 > len_max)
			{
    
    
				index = i;
				len_max = len0;
			}
		}
		else
		{
    
    
			len0 = 0;
		}
	}
	index = index- len_max+1;
	for (int i = index; i < index+ len_max; i++)
	{
    
    
		printf("%c", srt[i]);
	}
	if (len_max == 0)
	{
    
    
		printf("数字字符串为空\n");
		printf(" ");
	}
	printf("\n");
	printf("len_max=%d", len_max);
	printf("len_max=%d", len_max);


}

猜你喜欢

转载自blog.csdn.net/mao_hui_fei/article/details/113271254