【题目解析】:
设置一个start指针,从头开始遍历,遇到数字,使用end指针开始往后追(同时进行计数),就可以截取到一段数字(用tmp保存起来),更新start的位置,继续向字符串中找出连续最长的数字串后遍历,直到截取到下一次的数字,此时比较计数器的大小,从而决定保存哪一段数字。
大致的思路很简单,细节性的问题,还需要仔细考虑。
#include <iostream>
#include<string>
using namespace std;
int main() {
string str,ret = "wo ";
int count = 0;
getline(cin,str);
auto start = str.begin();
string tmp;
while(*start != '\0')
{
if(*start >= '0' && *start <= '9')
{
auto end = start;
int cur_cnt = 0;
tmp.clear(); //tmp的值必须提前清空
while(*end >= '0' && *end <= '9')
{
tmp += *end;
end++;cur_cnt++;
}
if(count < cur_cnt) // 因为要求最长字串,用例中应当没有等长的数串,则不考虑相等的情况
{
count = cur_cnt;
start = end;
ret = tmp;
}
else
{
start = end;
}
}
start++;
}
cout<<ret;
return 0;
}

京公网安备 11010502036488号