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

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

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

#include <iostream>
#include <vector>
using namespace std;
#include <string>
#include <cctype>
int main()
{
    string str;
    while (getline(cin, str))
    {
        int maxl = 0;
        vector<string> s;
        auto start = str.begin();
        auto end = str.begin();
        auto p = str.begin();

        bool lastD;
        if(isdigit(str[0])){
            lastD = true;
        }
        else{
            lastD = false;
        }
        for (int i = 0; i < str.size(); i++, p++)
        {
            if (isdigit(str[i]) && !lastD)
            {
                start = p;
                lastD = true;
            }
            else if (!isdigit(str[i]) && lastD && p != str.begin())
            {
                lastD = false;
                end = p;
                string temp(start, end);
                if (temp.size() > maxl)
                {
                    maxl = temp.size();
                }
                s.push_back(temp);
            }
        }
        if (lastD)
        {
            string temp2(start, str.end());
            if (temp2.size() > maxl)
            {
                maxl = temp2.size();
            }
            s.push_back(temp2);
        }
        for (auto &n : s)
        {
            if (n.size() == maxl)
            {
                cout << n;
            }
        }
        cout << "," << maxl << endl;
    }
}

边记录边存,最后输出即可

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务