题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
#include <cstdio>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
// 1. 找到所有数值子串
// 2. 统计其长度
// 3. 找到最长的输出
int main() {
string input;
input.reserve(210);
while (cin >> input) {
vector<int> pos_vec;
int maxlen = 0;
string sep = R"([\d]+)";
regex reg(sep);
sregex_iterator iter(input.cbegin(), input.cend(), reg);
sregex_iterator end;
for (; iter != end; ++ iter) {
if (iter->length() > maxlen) {
maxlen = iter->length();
pos_vec.clear();
pos_vec.push_back(iter->position());
} else if (iter->length() == maxlen) {
pos_vec.push_back(iter->position());
} else {
;
}
}
for (int i = 0; i < pos_vec.size(); ++ i) {
for (int pos = pos_vec.at(i); pos < pos_vec.at(i) + maxlen; ++ pos) {
putchar(input.at(pos));
}
}
cout << "," << maxlen << endl;
}
return 0;
}
// 64 位输出请用 printf("%lld")
查看20道真题和解析