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

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

https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec?tpId=37&tqId=21315&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=

思路:题目要求的是在字符串中找出一个或多个(长度一样)最大的子字符串,我的第一想法是先遍历一遍找出最大长度,然后再遍历一遍把符合要求的丢进vector<string>中,完成返回最大长度,再想了一下,发现可以改成记录子串的初始位置和校验下一个字符是不是数字来避免麻烦push和clear,代码实现如下:

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

bool checkNumberChar(char c){
    return c >= '0' && c <= '9';
}

int findMaxChildString(string& str, std::vector<string>& arrStr) {
    int maxlength = 0;
    std::vector<int> startIndexArray;
    for (int i = 0, startIndex = 0; str[i]; i++) {
        if (checkNumberChar(str[i])) {
            startIndex = i;
            while (checkNumberChar(str[i+1])) {
                i++;
            }
            int currentLenght = i - startIndex + 1;
            if(maxlength > currentLenght) continue;
            if (maxlength < currentLenght) {
                maxlength = currentLenght;
                startIndexArray.clear();
            }
            startIndexArray.push_back(startIndex);
        }
    }
    for (auto index : startIndexArray) {
        arrStr.push_back(str.substr(index, maxlength));
    }
    return maxlength;
}

int main() {
    string str;
    int len = 0;
    std::vector<string> subMaxStr;
    while (cin >> str) {
        len = findMaxChildString(str, subMaxStr);
        for (auto item : subMaxStr) {
            cout << item;
        }
        cout << ',' << len << endl;
        subMaxStr.clear();
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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