R7-1 jmu-ds-最长数字序列
输入一个字符串,求该字符串中最长连续数字序列出现的起始位置及其长度。
输入格式:
输入一个字符串,可包含空格。
输出格式:
输出内容:最长数字序列起始位置和长度空格隔开。输出尾部不能有空格。输入空串,输出"NULL"
输入样例:
123ab12345a
输出样例:
5 5
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string s;
getline(cin, s);
if (s.empty()) {
cout << "NULL" << endl;
return 0;
}
int maxStart = -1;
int maxLength = 0;
int currentStart = -1;
int currentLength = 0;
for (int i = 0; i < s.length(); i++) {
if (isdigit(s[i])) {
if (currentStart == -1) {
currentStart = i;
}
currentLength++;
if (currentLength > maxLength) {
maxStart = currentStart;
maxLength = currentLength;
}
} else {
currentStart = -1;
currentLength = 0;
}
}
if (maxLength > 0) {
cout << maxStart << " " << maxLength << endl;
} else {
cout << "NULL" << endl;
}
return 0;
}