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

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

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

//用vector数组存储最长数字子串,同时用maxlen变量存储最长数字子串的长度,temp变量存储新数字子串,将其长度与maxlen比较:
//更大的话将vector数组清空,加入新子串,temp变量赋为空字符串
//相等的话加入新子串,temp变量赋为空字符串
//否则,temp变量赋为空字符串
#include <asm-generic/errno.h>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    string input;
    while (getline(cin, input)) {
        vector<string> numstr;
        int maxlen = 0;
        string temp = "";
        for (int i = 0; i < input.length(); i++) {
            while (isdigit(input[i])) {
                temp += input[i];
                i++;
            }
            if (temp.length() > maxlen) {
                maxlen = temp.length();
                numstr.clear();
                numstr.push_back(temp);
                temp = "";
            } else if (temp.length() == maxlen && temp.length() != 0) {
                numstr.push_back(temp);
                temp = "";
            } else {
                temp = "";
            }
        }
        for (auto str : numstr) {
            cout << str;
        }
        cout << ',' << maxlen << endl;
    }
    return 0;
}

全部评论

相关推荐

09-24 17:57
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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