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

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

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

#include <cctype>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    string s;
    while (cin >> s) {
        string temp, target;
        int cnt = 0, max_cnt = 0;
        for (char& c : s) {
            if (isdigit(c)) {
                ++cnt;
                temp += c;
            } else {
                if (max_cnt <
                        cnt) //当连续数字长度大于之前的最大数字长度,把要输出的字符串清空
                    target.clear();
                max_cnt = max(max_cnt, cnt);
                if (max_cnt ==
                        cnt) //最大数字字符串长度==当前最长数字字符串长度,把当前数字字符串加入到要输出的目标字符串中
                    target = target + temp;
                cnt = 0;
                temp.clear();
            }
        }

        if (cnt > max_cnt) {  //最后遍历的数字字符串长度>以往最大的数字字符串长度
            max_cnt = cnt;
            target = temp;
        } else if (cnt == max_cnt) {//最后遍历的数字字符串长度==以往最大的数字字符串长度
            target = target + temp;
        }
        cout << target << "," << max_cnt;
        
    }
    return 0;
}

全部评论

相关推荐

码农索隆:以下是我以我微薄的认知提供的建议: 1.考个教师资格证,去当体育考试。 2.去健身房当健身教练(因为在我印象里面体育生身材都不错)。
点赞 评论 收藏
分享
牛至超人:您好,京东物流岗了解一下吗?负责精加工食品的端到端传输
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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