zoukankan      html  css  js  c++  java
  • 代码题(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;
    }

      

  • 相关阅读:
    [转]Navicat Premium 12试用期的破解方法
    Redis禁用持久化功能的设置
    阿里云ECS安装的redis服务器,用java代码去连接报错。
    关于Jedis连接Linux上的redis出现 DENIED Redis is running in protected mode问题的解决方案
    修改了jdk在环境变量中的路径怎么cmd中的jdk版本没有变
    阿里云上部署tomcat启动后,通过http不能访问
    【终结篇】不要再问我程序员该如何提高了……
    我是怎么把一个项目带崩的
    eterm和easyfare的官网地址
    java UTC时间和local时间相互转换
  • 原文地址:https://www.cnblogs.com/eilearn/p/9546940.html
Copyright © 2011-2022 走看看