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

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

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

#include<iostream>
#include<string>
#include<vector>
#include<unordered_map>
using namespace std;

int get_long_num(string& num_str) {
    int max_len = 0;
    int len = num_str.size();
    unordered_map<int, vector<int>>hash;
    for (int i = 0; i < len; i++) {
        if (num_str[i] >= '0' && num_str[i] <= '9') {
            int j = i + 1;
            while (num_str[j] >= '0' && num_str[j] <= '9') {
                j++;
            }
            if ((j - i) > max_len) {
                max_len = j - i;
                hash[max_len] = { i };
                i = j;
            } else if ((j - i) == max_len) {
                hash[max_len].push_back(i);
                i = j;
            }

        }
    }
    if (max_len == 0) {
        cout << "字符串中没有数字字符";
        return 0;
    } else if (max_len != 0) {
        auto it = hash.find(max_len);
        int len_out = it->second.size();
        for (int m = 0; m < len_out; m++) {
            for (int k = it->second[m]; k < max_len + it->second[m]; k++) {
                cout << num_str[k];
            }
        }
        cout << "," << max_len << endl;
    }
    return 0;
}
int main() {
    string str;
    while (getline(cin, str)) {
        get_long_num(str);
    }
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务