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

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

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

// 遍历字符串,记录最长的数字串,同时保存在vector数组中
#include <cctype>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    string str;
    while(cin >> str){
        int cur = 0, maxLen = 0, pos = 0;
        vector<string> ans;
        int len = str.length();
        for(int i = 0; i < len; ++i){
            if(isdigit(str[i])){
                cur++;
            }else{
                if(cur > maxLen){
                    ans.clear();
                    maxLen = cur;
                    pos = i - maxLen;
                    ans.push_back(str.substr(pos, maxLen));
                }
                else if(cur == maxLen){
                    pos = i - maxLen;
                    ans.push_back(str.substr(pos, maxLen));
                }
                cur = 0;
            }
        }
        if(cur > maxLen){
            ans.clear();
            maxLen = cur;
            pos = len - maxLen;
            ans.push_back(str.substr(pos, maxLen));
        }else if(cur == maxLen){
            pos = len - maxLen;
            ans.push_back(str.substr(pos, maxLen));
        }
        for(auto it : ans){
            cout << it;
        }
        cout << "," << maxLen<< endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

哥_留个offer先:跟他说,你这个最好用c#,微软就用c#Java不适合这个项目
点赞 评论 收藏
分享
05-09 12:23
已编辑
华南理工大学 Java
野猪不是猪🐗:给他装的,双九+有实习的能看的上这种厂我直接吃⑨✌们拿它练练面试愣是给他整出幻觉了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务