题解 | 字符串中找出连续最长的数字串
字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/bd891093881d4ddf9e56e7cc8416562d
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string str; cin >> str; int left = 0, right = 0; int max_len = 0; // 记录最长数字串的起始索引和长度 int start = 0, result_len = 0; while(right < str.size()) { // 如果当前字母不是数字, 重置左边界 if(!isdigit(str[right])) left = right + 1; // 当前窗口长度 int current_len = right - left + 1; // 更新最长数字串 if(current_len > result_len) { result_len = current_len; start = left; // 记录起始位置 } right++; } cout << str.substr(start, result_len) << endl; return 0; }
这道题的核心思路是 用滑动窗口(双指针)遍历字符串,动态维护连续数字子串的区间,同时记录最长数字子串的起始位置和长度,具体分以下几步:
- 滑动窗口初始化:用
left
和right
两个指针表示当前窗口的左右边界,初始都指向字符串起始位置。 - 遍历与窗口调整: 右指针 right 逐个字符遍历字符串。若遇到非数字字符,就把左指针 left 直接跳到 right + 1(让窗口重新从下一个位置开始找连续数字)。若遇到数字字符,窗口自然向右扩展(right 继续右移,left 保持不动)。
- 记录最长子串:每次窗口变化后(
right
移动),计算当前窗口长度right - left + 1
。若当前长度大于历史最长长度,就更新 “最长长度” 和 “最长子串的起始位置”。 - 截取并输出结果:遍历结束后,用
substr(起始位置, 最长长度)
截取字符串,输出最长连续数字子串。