好未来: 字符串中找出连续最长的数字串

题目链接:字符串中找出连续最长的数字串

#include<iostream>
#include<algorithm>
#include<cstring> 
using namespace std;
const int maxn = 1e6+5;
int main()
{
	char str[maxn];
	gets(str);
	int len=strlen(str);
	int maxv=0;				//用来保存最长数字串的长度 
	int max_pose=0;			//用来保存最长数字串的起始位置 
	for(int i=0;i<len;i++)	//遍历这个字符串 
	{
		if(str[i]-'0'>=0 && str[i]-'0'<=9)	//如果是数字的话 
		{
			int j=i;
			int ans=0;						//当前数字串长度 
			while(str[j]-'0'>=0 && str[j]-'0'<=9 && j<len)	//如果当前位置是数字,并且位置合法 
			{
				ans++;										 
				j++;
			}
			if(ans>maxv) 					//如果当前数字串比之前的长,则更新长度和位置 
			{
				maxv=ans;
				max_pose=i;	
			}
			i=j+1; 							//下次从这个数字串的末尾遍历就可以了 
		}
		
	}
	for(int i=max_pose;i<max_pose+maxv;i++)	//输出答案 
	{
		cout<<str[i];
	}
	cout<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/q1122333/article/details/82961687