代码题(58)— 字符串中找出连续最长数字串

0、在线测试问题:

  1、本地通过,但在线测试没有通过率的问题:

  解决方法:

  (1)将程序包在下面代码里面试一试。

while (cin >> str)
{
}

  (2)将程序别包含在上面代码中再试一试。

  2、考虑一下边界条件问题

1、题目描述一:读入一个字符串str,输出字符串str中的连续最长的数字串

    • 输入描述: 
      个测试输入包含1个测试用例,一个字符串str,长度不超过255。

    • 输出描述: 
      在一行内输出str中里连续最长的数字串。

    • 输入 
      abcd12345ed125ss123456789

    • 输出 
      123456789

   思路:循环判断每一个位置处的数字子串长度,保留最长子串。

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include <vector>
#include<string>
#include<sstream>
#include<map>
#include<set>
#include <functional> // std::greater
using namespace std;

int main()
{
    string str;
    cin >> str;
    int maxlen = 0;
    string res;
    for (int i = 0; i < str.size(); ++i)
    {
        if (str[i] >= '0'&& str[i] <= '9')
        {
            int temp = i;
            while (str[i] >= '0'&& str[i] <= '9')
                i++;
            if (maxlen <= i - temp)
            {
                maxlen = i - temp;
                res = str.substr(temp, maxlen);
            }
        }
    }
    cout << res << endl;
    system("pause");
    return 0;
}

2、读入一个字符串str,输出字符串str中的连续最长的数字串

输入描述: 个测试输入包含1个测试用例,一个字符串str,长度不超过255。

输出描述:在一行内输出str中里连续最长的数字串。

示例1:abcd12345ed125ss123456789
输出:123456789
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include <vector>
#include<string>
#include<sstream>
#include<map>
#include<set>
#include <functional> // std::greater
using namespace std;

int main()
{
    string str;
    while (cin >> str)
    {
        int maxlen = 0;
        string res;
        for (int i = 0; i < str.size(); ++i)
        {
            if (str[i] >= '0'&& str[i] <= '9')
            {
                int temp = i;
                while (str[i] >= '0'&& str[i] <= '9')
                    i++;
                if (maxlen < i - temp)
                {
                    maxlen = i - temp;
                    res = str.substr(temp, maxlen);
                }
                else if (maxlen == i - temp)
                    res += str.substr(temp, maxlen);
            }
        }
        cout << res << ',' << maxlen << endl;
    }
    
    system("pause");
    return 0;
}

  

原文地址:https://www.cnblogs.com/eilearn/p/9546940.html