题目描述
读入一个字符串str,输出字符串str中的连续最长的数字串
输入描述:
个测试输入包含1个测试用例,一个字符串str,长度不超过255。
输出描述:
在一行内输出str中里连续最长的数字串。
示例1
输入
abcd12345ed125ss123456789
输出
123456789
思路:注意各个变量的关系。具体的思路就看代码啦,坑点就是最后的如果是数字的话需要特别处理一下。
代码如下:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
string str;
cin >> str;
int length = str.size();
int maxL = 0, startT = 0, endT = 0, temp = 0,start = 0,end = 0;
bool flag = true;
for (int i = 0; i < length; i++)
{
//cout <<"flag:"<< flag << endl;
if (str[i] >= '0' && str[i] <= '9' && flag) {
flag = false;
temp++;
//cout << "temp:" << temp << endl;
startT = i;
endT = i;
}
else if (str[i] >='0' && str[i] <= '9') {
temp++;
//cout << "temp:" << temp << endl;
endT++;
}
else {
if (temp > maxL) {
maxL = temp;
start = startT;
end = endT;
}
temp = 0;
flag = true;
}
}
if (temp > maxL) {
maxL = temp;
start = startT;
end = endT;
}
//cout << start << endl;
//cout << end << endl;
for (int i = start; i <= end; i++) cout << str[i];
cout << endl;
system("pause");
return 0;
}