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

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

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

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    while (cin >> s) { // 注意 while 处理多个 case
        size_t pos = 0;
        int count = 1;
        int maxlen = 0;
        vector<string> res;
        for(int i = 0; i < s.size(); ++i){
            if(isdigit(s[i])){
                pos = i;
                break;
            }
        }
        int i = pos + 1;
        for(; i < s.size(); ++i){
            if(isdigit(s[i]) && isdigit(s[i - 1])){
                ++count;
            }
            else if(!isdigit(s[i]) && isdigit(s[i - 1])){
                if(count > maxlen){
                    maxlen = count;
                    
                    res.clear();
                    res.emplace_back(s.substr(pos, i - pos));
                }
                else if(count == maxlen){
                    res.emplace_back(s.substr(pos, i - pos));
                }
                //查找下一个数字起始位置
                pos = s.find_first_of("0123456789", i);
                if(pos == std::string::npos){
                    count = 0;  //后面没有数字了
                    break;
                }
                i = pos;  //i应该变为 pos + 1,加一的工作交给 ++i去做了,否则会错误 
                count = 1;
            }
        }
        if(count > maxlen){
            res.clear();
            res.emplace_back(s.substr(pos, i - pos));
        }
        else if(count == maxlen){
            res.emplace_back(s.substr(pos, i - pos));
        }
        for(string &str : res){
            cout << str;
        }
        cout << "," << res[0].length() << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

darius_:我试了简历上有微服务和没微服务主动要简历的外包的比例都不一样,微服务稍微看看还是要写上去,人人都写你不写会被pass
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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