首页 > 试题广场 >

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

[编程题]在字符串中找出连续最长的数字串
  • 热度指数:137939 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
输入一个字符串,返回其最长的数字子串,以及其长度。若有多个最长的数字子串,则将它们全部输出(按原字符串的相对位置)
本题含有多组样例输入。

数据范围:字符串长度 , 保证每组输入都至少含有一个数字

输入描述:

输入一个字符串。1<=len(字符串)<=200



输出描述:

输出字符串中最长的数字字符串和它的长度,中间用逗号间隔。如果有相同长度的串,则要一块儿输出(中间不要输出空格)。

示例1

输入

abcd12345ed125ss123058789
a8a72a6a5yy98y65ee1r2

输出

123058789,9
729865,2

说明

样例一最长的数字子串为123058789,长度为9
样例二最长的数字子串有72,98,65,长度都为2    
import java.util.*;
public class lianxu{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
            String str = scan.next();
            ArrayList<String> list = new ArrayList<String>(); 
            for(int i=0;i<str.length();i++){
                for(int j=i+1;j<str.length();j++){
                    if(str.charAt(i)>='0'&&str.charAt(i)<='9'){
                        if(
                      str.charAt(j)>='0'&&str.charAt(j)<='9'){
                        	if(j==str.length()-1){
                        		list.add(str.substring(i, str.length()));
                        	}
                    } else{
						list.add(str.substring(i,j));
                            break;
                        }
                    }
                    else{
                       continue;
                    }
                   
                }
            }
           int max = 0;
           for(int i=0;i<list.size();i++) {
        	   if(list.get(i).length()>max){
        		   max=list.get(i).length();
        	   }
           }
           StringBuilder sb = new StringBuilder();
            for(int i=0;i<list.size();i++){
            	if(list.get(i).length()==max){
            		//System.out.println(list.get(i)+","+max);
            		sb.append(list.get(i));
            	}
            }
            System.out.println(sb+","+max);
        }
        }
    }
}
这题太坑了,字符串长度一样的竟然同时输出
发表于 2016-06-17 11:07:07 回复(2)
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
void print(string str) {
	string res, tmp;
	int len = 0;
	stringstream ss;
	ss << str;
	while (getline(ss, tmp, ' '))
		if (tmp[0] != ' ' && tmp.size() == len) res += tmp;
		else if (tmp[0] != ' ' && tmp.size() > len) {
			res = tmp;
			len = tmp.size();
		}
	cout << res << "," << len << endl;
}
int main() {
	string str;
	while (getline(cin, str)) {
		for (int i = 0; i < str.size();i++) if (!isdigit(str[i])) str[i] = ' ';
		print(str);
	}
}

发表于 2017-03-20 16:19:22 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while((str = br.readLine()) != null) {
            String[] arr = str.split("[A-Za-z]+");
            int len = 0;
            for (int i = 0; i < arr.length; i++) {
                // System.out.println(arr[i]);
                if(arr[i].length() > len) { len = arr[i].length(); }
            }
            for (int i = 0; i < arr.length; i++) {
                if(arr[i].length() == len) {
                    System.out.print(arr[i]);
                }
            }
            System.out.println("," + len);
        }
    }
}

发表于 2022-08-02 23:04:07 回复(0)
while True:
    try:
        str_in = input()
        def substr_num(s:str):
            # 将所有字母替换为‘ ’
            cur_s = ''
            for x in s:
                if x.isdigit():
                    cur_s += x
                else:
                    cur_s += ' '
            lst_num = cur_s.split(' ')
            sub_num = []
            # 生成数字子串
            for num in lst_num:
                if num != '':
                    sub_num.append(num)
            # 找到数字子串中的最长长度
            max_len = 0
            for y in sub_num:
                max_len = max(max_len, len(y))
             # 查找长度等于len的子串并输出
            target_str = ''
            for z in sub_num:
                if len(z) == max_len:
                    target_str += z
            print(f'{target_str},{max_len}')
        substr_num(str_in)
    except:
        break

发表于 2022-07-30 18:57:20 回复(0)
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    string s;
    int n;
    
    int count;
    while(getline(cin,s)){
        count = 0;
        n = s.size();
        vector<int> arr(n+1);
        //cout<<n;
        for(int i=n;i>=0;i--) arr[i] = 0;
        
        for(int i = n-1;i>=0;i--){
            if(s[i]>='0'&&s[i]<='9'){
                arr[i] = arr[i+1]+1;
                //cout<<arr[i];
                if(arr[i]>count) count = arr[i];                
            }          

        }
        for(int i = 0;i<n;i++){
            if(arr[i]==count){
                for(int j=i;j<i+count;j++) {cout<<s[j];}
                continue;                    
            }
        }
        cout<<','<<count<<endl;
    }
    
}
发表于 2022-07-24 00:43:31 回复(0)
python 
# coding: utf-8
import re
def func(s):
    max_str = ''
    nums = re.findall(r'\d+', s)
    max_length = len(max(nums,key=len))
    for i in nums:
        if len(i) == max_length:
            max_str += i
    print max_str + ',' + str(max_length)
if __name__ == "__main__":
    import sys
    try:
        while True:
            line1 = sys.stdin.readline().strip()
            func(line1)
    except:
        pass


发表于 2022-04-14 23:49:11 回复(0)
import re
while True:
    try:
        a = input()
        b = re.findall('\d+', a)
        c = max(list(map(len, b)))
#         print(c)
        d = []
        for i in b:
            if len(i) == c:
                d.append(i)
        e = ''.join(d)
        print(f'{e},{c}')
    except:
        break
发表于 2022-04-12 00:16:52 回复(0)
直接按照长度保存字符串,最后输出即可,只要遍历一遍!
#include<bits/stdc++.h>
using namespace std;
int main(){
    string a;
    while(getline(cin,a)){
        string b[201];
        int max=0,len=0;
        for(int i=0;i<a.size();i++){
            if(a[i]>='0'&&a[i]<='9')
                len++;
            else if(len!=0){
                max=(max>len)?max:len;
                b[len]=b[len]+a.substr(i-len,len);
                len=0;
            }
        }
        if(len!=0){
            b[len]=b[len]+a.substr(a.size()-len,len);
            max=(max>len)?max:len;
        }
        cout<<b[max]<<","<<max<<endl;
    }
}
发表于 2022-03-27 15:11:51 回复(0)
苯办法,采取一趟遍历,中途嵌套遍历连续子串
#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main(){
    string s;
    while(cin>>s){
        int len = s.length();
        int maxLen = 0;
        vector<string> res;
        for(int i=0;i<len;i++){
            if(isdigit(s[i])){     // 若当前是数子,则考虑继续往后遍历
                int j,cot=0;        // 以j=i作为遍历连续数子的起点
                for(j=i;j<len && isdigit(s[j]);j++) cot++;
                if(maxLen<cot){          // 更新最大长度
                    maxLen = cot;
                    res.clear();          // 之前的片段不再最大,先清空,再重新装入最大片段
                    res.push_back(s.substr(i,j-i));
                }
                else if(maxLen==cot){
                    res.push_back(s.substr(i,j-i));  // 长度相等时,再加入这个相等长度
                }
            }
        }
        for(int i=0;i<res.size();i++) cout<<res[i];
        cout<<","<<maxLen<<endl;
    }
}

发表于 2022-01-13 10:53:13 回复(0)
之前中等里面的最长公共子串问题的变体,当时学习到一个很巧妙的tmp方法,
while True:
    try:
        n = input()
        tmp = 0
        res = []
        for i in range(len(n)):
            if n[i-tmp:i+1].isdigit():
                tmp += 1
        for i in range(len(n)-tmp+1):
            if n[i:i+tmp].isdigit():
                res.append(n[i:i+tmp])
        print("".join(res) + "," + str(tmp))
    except:
        break


发表于 2021-12-17 03:23:55 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String str="";
        while ((str=br.readLine())!=null){
            int maxLen=0;
            int len=0;
            //关键 利用正则表达式来获取所有的连续数字字符串
            String[] split = str.split("[^0-9]");
            List<String> list=new ArrayList<>();
            for (String s:
                 split) {
                //把长度直接带在字符串末尾
                    list.add(s+s.length());
            }
            for (String s:
                 list) {
                len=s.charAt(s.length()-1)-48;
                if(len>maxLen){
                    maxLen=len;
                }
            }
            for (String s:list){
                    if((s.charAt(s.length()-1)-48)==maxLen){
                        System.out.print(s.substring(0,s.length()-1));
                    }
                }
            System.out.print(","+maxLen);
            System.out.println();
        }
    }
}

发表于 2021-09-07 00:36:49 回复(0)
while 1:
    try:
        s=input()
        n=len(s)
        ss=''
        for i in range(n):
            if s[i] in '1234567890':
                ss+=s[i]
            else:
                ss+='a'
        l=list(map(str,ss.split('a')))
        maxlen=0
        res=''
        for j in l:
            if len(j)>maxlen:
                maxlen=len(j)
                res=j
            elif len(j)==maxlen:
                res+=j
        print('{},{}'.format(res,maxlen))
    except:
        break

发表于 2021-07-22 15:57:07 回复(0)
快慢双指针法
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
int main() {
    string s;
    while(getline(cin, s)) {
        
        int low = 0, fast = 0;
        map<int, vector<string>> miv;
        while(fast != s.size()) {
            if(!isdigit(s[low]) && !isdigit(s[fast])) {
                low++;
                fast++;
            }
            if(isdigit(s[low])) {
                while(isdigit(s[fast])) {
                    fast++;
                }
                miv[fast - low].push_back(s.substr(low, fast-low));
                low = fast;
            }
        }
        map<int, vector<string>>::reverse_iterator mri = miv.rbegin();
        for(int i = 0; i < mri->second.size(); i++)  cout << mri->second[i];
        cout << ',' << mri->first << endl;
    }
    return 0;
}
发表于 2021-06-30 15:01:08 回复(0)
#include<stdio.h>
#include<string.h>
int main(void)
{
    char str[1000];
    char num[1000];
    int  count = 0;i
    nt  max   = 0;
    /*思想就是 把字符串刚出现数字的下标记下来,以及连续出现自然数的个数放在那个下标下
   后续通过下标及个数去取字符串*/
    while (scanf("%s",str) != EOF)
    {
        memset(num, 0, sizeof(num));
        max = 0;
        count = 0; //第一组字符串末尾是数字,第二组字符串开头是数字,count没清掉会出问题
        for(int i = 0; i < strlen(str);)
        {
            if((str[i]>= '0') && (str[i]) <= '9')
            {
                count++;
                i++;
                if (count > max)
                {
                    max = count;
                }
                num [i - count] = count;
                continue;
            }
            else
            {
                i++;
                count = 0;
            }
        }
        for (int i = 0; i < sizeof(num); i++)
        { 
            if(num[i] == max)
            {
                for(int j = i; j < i + max; j++)
                {
                    printf("%c",str[j]);
                }
            }
        }
        printf(",%d\n",max);
        //memset(str, 0, sizeof(str));
    }
    return 0;
}
编辑于 2021-04-29 00:32:45 回复(0)
投机方法:利用正则表达式匹配出原串中所有的数字串,然后按照长度和在原串中的位置分别进行降序和升序的二次排序。将最前面的几个长度相同的子串拼接起来即可。
import re

while True:
    try:
        line = input().strip()
        # 用正则表达式匹配出所有连续数字子串,然后按子串长度降序排列
        lst = sorted([(i, substr, len(substr)) for i, substr in enumerate(re.findall("[0-9]+", line))], key=lambda x: (-x[2], x[0]))
        res, length = [lst[0][1]], lst[0][2]
        for i in range(1, len(lst)):
            if lst[i][2] == length:
                res.append(lst[i][1])
            else:
                break
        print(f"{''.join(res)},{length}")
    except:
        break
发表于 2021-03-26 11:45:28 回复(0)
#1
while 1:
    try:
        s = input()
        res, l, i = '', 0, 0
        while i < len(s)-1:
            if s[i].isdigit():
                temp = s[i]
                for j in range(i+1, len(s)):
                    if s[j].isdigit():
                        temp += s[j]
                    else:
                        i = j
                        break
                if len(temp) > l:
                    res = temp
                    l = len(temp)
                elif len(temp) == l:
                    res += temp
            i += 1
        print(res+','+str(l))
    except EOFError:
        break
#2
while True:
    try:
        s = input()
        for i in s:
            if not i.isdigit():
                s = s.replace(i, ' ')
        l = len(max(s.split(),key=len))
        res = [i for i in s.split() if len(i) == l]
        print(''.join(res)+','+str(l))
    except EOFError:
        break

编辑于 2021-02-02 15:48:56 回复(0)
Java:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String[] sa = scan.nextLine().split("[^0-9]+");
            Arrays.sort(sa, (s1, s2) -> s2.length() - s1.length());
            StringBuilder sb = new StringBuilder();
            for (int i = 0, max = sa[0].length(); i < sa.length; i++) {
                if (sa[i].length() != max) break;
                sb.append(sa[i]);
            }
            System.out.println(sb.toString() + "," + sa[0].length());
        }
    }
}

C++:
#include <iostream>
#include <regex>
#include <algorithm>

using namespace std;

vector<string> split(const string &str, string &reg_str) {
    regex r(reg_str);
    sregex_token_iterator start(str.begin(), str.end(), r, -1), end;
    return vector<string>(start, end);
}

int main() {
    string s, reg = "[^0-9]+";
    while (cin >> s) {
        vector<string> v = split(s, reg);
        sort(v.begin(), v.end(), [](string &a, string &b) { return a.length() > b.length(); });
        int max = v[0].length();
        for (string &t: v) {
            if (t.length() != max) break;
            cout << t;
        }
        cout << "," << max << endl;
    }
    return 0;
}
C:
#include <stdio.h>
#include <string.h>

#define SIZE 4096

int main() {
    char s[SIZE] = {0};
    while (scanf("%s", s) != EOF) {
        int len = strlen(s), flag = 0, count = 0;
        char r[SIZE] = {0}, *pa[SIZE] = {0}; //用指针数组保存数字字符串起始地址
        for (int i = 0, idx = 0; i <= len; i++) {
            if (i < len && s[i] >= '0' && s[i] <= '9') {
                if (!flag) flag = 1, pa[count++] = &r[idx]; //记录每个数字字符串起始地址
                r[idx++] = s[i];
            } else {
                if (flag) flag = 0, r[idx++] = '\0';
            }
        }

        for (int i = 0, max = 0; i < count; i++, max = i) { //排序
            for (int j = i + 1; j < count; j++) {
                if (strlen(pa[j]) > strlen(pa[max])) max = j;
            }
            char *tmp = pa[max];
            pa[max] = pa[i];
            pa[i] = tmp;
        }

        int max = strlen(pa[0]);
        for (int i = 0; i < count; i++) { //输出长度为max的数字字符串
            if (strlen(pa[i]) != max) break;
            printf("%s", pa[i]);
        }
        printf(",%d\n", max);
    }
    return 0;
}

编辑于 2021-01-30 17:00:05 回复(0)
# 思路:将不是数字的字符全部变成‘a’,再将字符串用a来分割称数组,
#      长度最大的数组的长度即为所求的长度

while True:
    try:
        s = input().strip()
        new_s = ''
        for ch in s:
            if not ch.isdigit():
                new_s += 'a'
            else:
                new_s += ch
        digit_list = list(filter(lambda s: s.isdigit(), new_s.split('a')))
        max_len = max(map(len, digit_list))
        max_len_digit = []
        for digit in digit_list:
            if len(digit) == max_len:
                max_len_digit.append(digit)
        res_str = ''.join(max_len_digit)
        print(res_str+','+str(max_len))
    except:
        break

发表于 2020-12-09 16:44:18 回复(0)
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String s1 = sc.nextLine();
            System.out.println(getLongestNumString(s1));
        }
    }
        public static String getLongestNumString(String input){
        int start = 0;
        int end = 0;
        int res = 0;
        StringBuilder sb = new StringBuilder();
        Map<String,Integer> map = new LinkedHashMap<>();
        for(int i = 0 ; i < input.length(); i++){
            if(Character.isDigit(input.charAt(i))){
                start = i;
                end = i ;
                while(end < input.length() && Character.isDigit(input.charAt(end))){
                    end++;
                }
                res = Math.max(res, end - start );

                map.put(input.substring(start, end), end - start);
                i = end - 1;
            }
        }

        for(String s : map.keySet()){
            if(map.get(s).equals(res)){
                sb.append(s);
            }
        }
        sb.append(",");
        sb.append(res);
        return  sb.toString();
    }   
}
双指针菜鸟解法 
发表于 2020-12-03 01:08:53 回复(0)
纯C的噩梦

#include <stdio.h>
#include <string.h>
#include <ctype.h>
typedef struct{
    int x;
    int y;
}point; //一个结构体,存放所有数字段的起始位置
int an[100]={0}; //存放所有数字段的长度
int s=0; //数字段的个数
int max=0;//最长数字段的长度
point stack[100]; //定义100个

void fun(char *a)
{
    int len=strlen(a);
    int i,j,num=1;
    for ( i=0;i<len;i++)
    {
        if (isdigit(a[i])) //如果检测到数字了
        {
            num=1; //数字的个数起始就有一个了
            stack[s].x=i;//数字开始位置记下来
            for ( j=i+1;j<len;j++) //从下一个开始检测
            {

                if (!isdigit(a[j])) //如果当前字符不是数字
                {
                    stack[s].y=j-1; //就把上一个字符的位置记下来
                    break;
                }
                else  //如果是数字
                {
                 if (j==len-1) stack[s].y=j; //如果已经检测到最后一个了仍然还是数字就把最后的位置记下来
                 num++; //该数字段的数量++
                }
            }
            an[s++]=num; //把数字段的数字数量记下来
            i=j; //关键一步,跳过中间数字段,改变i的值
        }
    }
    max=an[0];
    for (i=1;i<s;i++) //寻找最长的数字段
    {
        if (an[i]>max) max=an[i];

    }

    for (i=0;i<s;i++) //输出最长数字段的数字
    {
        if (an[i]==max) //只要该长度为最长就输出
        {
            for (j=stack[i].x;j<=stack[i].y;j++) //根据记下来的起始位置即可输出
            printf("%c",a[j]);

        }

    }
    printf(",%d\r\n",max);//输出最大的长度
}

int main ()
{
    char str[100];
    while (scanf("%s",&str)!=EOF)
    {
        s=0;
        max=0;
        fun(str);
    }

}


发表于 2020-09-15 18:57:52 回复(0)