HJ92 题解 | #在字符串中找出连续最长的数字串#

在字符串中找出连续最长的数字串

https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <bits/stdc++.h>
#include <cmath>
using namespace std;

string GetMaxSubDigitStr(const string &s, int &maxLen)
{
    string res;
    int left = 0, right = 0;
    int maxSubDigitCnt = 0;

    for (int i = 0; i < s.size(); i++){
        int digitCnt = 0;
        if (!isdigit(s[i])) {
            continue;
        }
        digitCnt++;
        int right = i + 1;
        for (int j = i + 1; j < s.size(); j++) {
            if (isdigit(s[j])) {
                digitCnt++;
                right = j;
            } else {
                //right = j + 1;
                break;
            }
        }
        if (digitCnt == maxSubDigitCnt) {
            res += s.substr(i, right - i + 1);
        }
        if (digitCnt > maxSubDigitCnt) {
            res.clear();
            res += s.substr(i, right - i + 1);
            maxSubDigitCnt = digitCnt;
            maxLen = maxSubDigitCnt;
        }
    }

    return res;
}

int main() {
    string s;
    while (cin >> s) { // 注意 while 处理多个 case
        int maxLen = 0;
        string res = GetMaxSubDigitStr(s, maxLen);
        cout << res << "," << maxLen << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务