首页 > 试题广场 >

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

[编程题]在字符串中找出连续最长的数字串
  • 热度指数:139181 时间限制: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.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            // 接收输入的字符串
            String str = in.nextLine();
            // 加上一个字母防止不统计最后的数字串
            char[] chs = (str+"a").toCharArray();
            // 最大长度
            int maxLength = 0;
            // 临时字符串中数字串的大小
            int tempSize = 0;
            // 创建map存放结果,key为数字串的长度, value是具体字符串
            Map<Integer, String> map = new HashMap<>();
            for(int i = 0; i< chs.length; i++) {
                if(Character.isDigit(chs[i])) {
                    // 如果是数字,直接tempSize+1即可
                    tempSize ++;
                } else {
                    // 不是数字,需要判断tempSize是否大于等于最大数字串长度
                    if(maxLength == tempSize) {
                        // 相等的话,需要将i-tempSize 到i的数字串添加进结果中
                        map.put(tempSize, map.getOrDefault(tempSize, "") + str.substring(i-tempSize, i));
                    } else if(maxLength < tempSize) {
                        // tempSize大于maxLength,清空map,同时把该数字串加入结果map中
                        map.clear();
                        map.put(tempSize, str.substring(i-tempSize, i));
                        maxLength = tempSize;
                    }
                    // 不是字符串,需要将临时变量置为0
                    tempSize = 0;
                }
            }
            // 最后直接输出结果
            System.out.println(map.getOrDefault(maxLength, "") + "," + maxLength);
        }
    }
}
发表于 2024-05-22 10:52:58 回复(0)

import java.util.*;

/**
 * @Classname Main
 * @Description TODO
 * @Date 2024/4/17 16:17
 * @Created by admin
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String next = sc.next();
            int length = next.length();
            int[][] dp = new int[length][length];
            char[] arr = next.toCharArray();
            for (int i = 0; i < length; i++) {
                if (arr[i] >= '0' && arr[i] <= '9') {
                    dp[i][i] = 1;
                }
            }
            // 先进行end循环
            int max = 0;
            int start = 0;
            int end = 0;
            for (int i = 1; i < length; i++) {
                if (arr[i] >= '0' && arr[i] <= '9') {
                    for (int j = i - 1; j >= 0; j--) {
                        if (arr[j] >= '0' && arr[j] <= '9') {
                            dp[j][i] = dp[j + 1][i] + 1;
                            if (max < dp[j][i]) {
                                max = dp[j][i];
                                start = j;
                                end = i;
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < length; i++) {
                if (arr[i] >= '0' && arr[i] <= '9') {
                    for (int j = i; j < length; j++) {
                        if (arr[j] >= '0' && arr[j] <= '9') {
                            if (dp[i][j] == max){
                                map.put(i, j);
                            }
                        }
                    }
                }
            }
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                sb.append(next, entry.getKey(), entry.getValue() + 1);
            }
            System.out.println(sb + "," + max);
        }
    }
}

发表于 2024-04-20 13:01:14 回复(0)
import java.util.Scanner;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Iterator;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.next();
            System.out.println(getMaxString(str).getKey() + "," + getMaxString(
                                   str).getValue());
        }
    }
    public static Map.Entry<String, Integer> getMaxString(String str1) {
        StringBuilder sb = new StringBuilder("");
        LinkedHashMap <String, Integer> hm = new LinkedHashMap();
        for (int i = 0; i < str1.length();) {
            char c = str1.charAt(i);
            if (c >= '0' && c <= '9') {
                sb.append(c);
                i++;
                if (i < str1.length()) {
                    char c2 = str1.charAt(i);
                    if (c2 >= '0' && c2 <= '9') {
                        continue;
                    } else {
                        hm.put(sb.toString(), sb.length());
                        sb.replace(0, sb.length(), "");

                    }
                } else if (i == str1.length()) {
                    char c2 = str1.charAt(i - 1);
                    if (c2 >= '0' && c2 <= '9') {
                        hm.put(sb.toString(), sb.length());
                    } else {
                        hm.put(String.valueOf(str1.charAt(i)), 1);
                    }
                }
            } else {
                i++;
            }
        }
        int max = 0;
        //求得长度最大值
        for (Map.Entry<String, Integer> entry : hm.entrySet()) {
            if (entry.getValue() > max) {
                max = entry.getValue();
            }
        }
        sb.replace(0, sb.length(), "");
        //迭代器遍历删除小于最大值的元素
        Iterator<Map.Entry<String, Integer>> it = hm.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Integer> entry = it.next();
            if (entry.getValue() < max) {
                it.remove();
            } else {
                //相同长度的字符串拼接在一起
                sb.append(entry.getKey());
            }
        }
        hm.clear();
        hm.put(sb.toString(), max);
        for (Map.Entry<String, Integer> entry : hm.entrySet()) {
            return entry;
        }
        return null;
    }
}

发表于 2024-03-28 17:30:48 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String s = in.nextLine();
            String[] sp = s.split("[^\\d]+");
            int maxLength = 0;
            String result = "";
            for (int i = 0; i < sp.length; i++) {
                if (maxLength < sp[i].length()) {
                    result = sp[i];
                    maxLength = sp[i].length();

                } else if (maxLength == sp[i].length()) {
                    result = result + sp[i];
                }
            }

            System.out.println(result + "," + maxLength);
        }
    }
}
核心就是正则表达式,识别分割符是非数字
发表于 2024-03-28 14:40:28 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNextLine()){
            String s = in.nextLine();
            List<String> list = new ArrayList();
            int max = 0;
            int[] dp = new int[s.length()+1];
            for(int i = 1; i <= s.length(); i++){
                if(Character.isDigit(s.charAt(i-1))){
                    dp[i] = dp[i-1] +1;
                    if(dp[i] == max){
                        list.add(s.substring(i-max, i));
                    }else if(dp[i] > max){
                        max = dp[i];
                        list.clear();
                        list.add(s.substring(i-max, i));
                    }
                }
            }
            list.forEach(k->System.out.print(k));
            System.out.println(","+ max);
        }
    }
}

发表于 2023-11-28 16:14:24 回复(0)
import java.lang.Math;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String inputStr = in.nextLine();
            String[] strSplit = inputStr.replaceAll("[^0-9]", ",").split(",");

            // 计算最长长度
            int maxLeng = 0;
            for (String a : strSplit) {
                maxLeng = Math.max(maxLeng, a.length());
            }
            for (String a : strSplit) {
                if (a.length() == maxLeng) {
                    System.out.print(a);
                }
            }
            System.out.print("," + maxLeng + "\n");

        }
    }
}

发表于 2023-10-19 21:57:35 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (in.hasNext()) { // 注意 while 处理多个 case
            char[] str=in.nextLine().toCharArray();
            int[] DP=new int[str.length+1];
            List<Integer> list=new ArrayList<>();
            int max=0;
            for(int i=1;i<=str.length;i++){
                if(str[i-1]>='0'&&str[i-1]<='9'){
                    DP[i]=DP[i-1]+1;
                    if(DP[i]>max){
                        if(!list.isEmpty()){
                            list.clear();
                            list.add(i-1);
                            max=DP[i];
                        }else{
                            list.add(i-1);
                            max=DP[i];
                        }
                    }else if(DP[i]==max){
                        list.add(i-1);
                    }
                }
            }
            for(int i=0;i<list.size();i++){
                int index=list.get(i)-max+1;
                for(int j=0;j<max;j++){
                    System.out.print(str[index+j]);
                }
            }
            System.out.println(","+max);
        }
    }
}

发表于 2023-09-09 21:05:05 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = null;
        while ((str = br.readLine()) != null) {
            int k = 0, count = 0, startIndex = 0, currentIndex = 0;
            StringBuilder sb = new StringBuilder();
            int length = str.length();
            for (int i = 0; i < length; i++) {
                char ch = str.charAt(i);
                if ('0' <= ch && ch <= '9') {
                    count++;
                    if (k < count) {
                        k = count;
                        currentIndex = startIndex;
                        // 清空 StringBuilder
                        sb.setLength(0);
                    } else if (k == count) {
                        sb.append(str.substring(currentIndex, k + currentIndex));
                        currentIndex = startIndex;
                    }
                } else {
                    count = 0;
                    //当前分支是非数字,需要+1
                    startIndex = i + 1;
                }
            }
            System.out.println(sb.append(str.substring(currentIndex,
                                         k + currentIndex) + "," + k));
        }
    }
}


发表于 2023-07-18 14:56:36 回复(0)
import java.util.*;
import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (in.hasNextLine()) {
            String input = in.nextLine();

            Pattern p = Pattern.compile("[0-9]+");
            Matcher m = p.matcher(input);

            int length = 0;
            String numStr = "";
            while (m.find()) {
                String nums = m.group();
                if (nums.length() > length) {
                    length = nums.length();
                    numStr = nums;
                } else if (nums.length() == length) {
                    numStr += nums;
                }
            }
            System.out.println(numStr + "," + length);
        }
    }
}

发表于 2023-07-01 02:00:34 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.nextLine();
            System.out.println(maxNum(str));
        }
    }

    private static String maxNum(String str) {
	  	//使用空格替换所有的字符,仅留下数字
        String s = str.replaceAll("[A-Za-z]"," ");
	  	//根据空格拆分出数字串
        String[] split = s.split(" ");
        String max = "";
        StringBuilder sb = new StringBuilder();
        for (String value: split) {
		  	//找到最长的数字串
            if(value.length() > max.length()){
                max = value;
			  	//将max保存到sb中
                sb = new StringBuilder(max);
            }//数字串长度相等,就直接保存到sb中
            else if (value.length() == max.length()){
                sb.append(value);
            }
        }
	  	//最后保存逗号和最长数字串的长度
        sb.append(",").append(max.length());
        return sb.toString();
    }
}

发表于 2023-04-21 16:17:02 回复(0)
  Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str = in.next();
            TreeMap<Integer,String> treeMap = new TreeMap<Integer,String>();
            for(int i=0;i<str.length();i++){
                for(int j=str.length();j>=i;j--){
                    String subStr = str.substring(i,j);
                    if(subStr.matches("[0-9]+")){
                       if(treeMap.containsKey(subStr.length())){
                         treeMap.put(subStr.length(),treeMap.get(subStr.length())+subStr);
                       }else{
                          treeMap.put(subStr.length(),subStr);
                       }    
                    }
                }
            }
            System.out.println(treeMap.lastEntry().getValue()+","+treeMap.lastEntry().getKey());
        }
发表于 2023-04-12 23:53:23 回复(0)
import java.util.Scanner;
import java.util.*;
import java.util.Scanner;
import java.util.regex.Pattern;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String str = scanner.nextLine();
            List<String> list = new ArrayList<>();
            int len = 0;
            Pattern pattern = Pattern.compile("[0-9]+");
            int k = str.length();
            for (int i = 0; i < k; i++) {
                for (int j = k; j > i; j--) {
                    String tmp = str.substring(i, j);
                    if (pattern.matcher(tmp).matches()) {
                        if (tmp.length() > len) {
                            len = tmp.length();
                            list.clear();
                            list.add(tmp);
                        } else if (tmp.length() == len) {
                            list.add(tmp);
                        }
                        break;
                    }
                }
            }
            String result = "";
            for (String strr : list) {
                result += strr;
            }
            System.out.println(result + "," + len);
        }
    }
}

发表于 2023-02-26 23:14:11 回复(0)
这个就不说了,主要难点是将字符串中的数字分割处理,其他没啥
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            // 获取字符串
            String str = in.nextLine();
            // 将字符串中的数字字串拆分到数组中
            String[] numStrs = str.split("[^0-9]+");
            // 定义一个集合,用于存储字符串中最大的数字字串
            List<String> maxNumList = new ArrayList<>();
            // 定义一个变量,用于表示最长数字字串的最大长度
            int maxLength = 0;
            // 通过循环查找最大的数字字串
            for (int i = 0; i < numStrs.length; i++) {
                if (numStrs[i].length() > maxLength) {
                    // 先清空
                    maxNumList.clear();
                    // 最大字串添加进入列表
                    maxNumList.add(numStrs[i]);
                    // 求最大长度
                    maxLength = numStrs[i].length();
                } else if (numStrs[i].length() == maxLength) {
                    maxNumList.add(numStrs[i]);
                    maxLength = numStrs[i].length();
                }
            }
            // 输出最大数字字串结果
            maxNumList.forEach(p-> {
                System.out.print(p);
            });
            // 输出长度
            System.out.println("," + maxLength);
        }
    }
}


发表于 2023-02-14 10:43:34 回复(0)
1.遍历所有子字符串,如果全部是数字,存到map 中,
2.小技巧,key=子串length, value=子串。如果有相同length的子串,把子串添加到后面。3.最后倒排序key,key的最大值就是原始字符串的长度, 找到第一个就是结果。
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String string = scanner.nextLine();
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < string.length(); i++) {
for (int j = i + 1; j < string.length() + 1; j++) {
String tempString = string.substring(i, j);
int k = tempString.length();
if (tempString.matches("\\d+")) {
if (map.get(k) != null) {
map.put(k, map.get(k) + tempString);
} else {
map.put(k, tempString);
}
}
}
}

for (int i = string.length(); i > 0; i--) {
if (map.get(i) != null) {
System.out.println(map.get(i) + "," + i);
break;
}
}
}
}
}
发表于 2023-02-08 18:39:45 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while(in.hasNext()){
            String[] strArr=in.nextLine().split("[^0-9]+");
            // Arrays.sort(strArr);
            ArrayList<String> list=new ArrayList<>();
            String str="";
            for(int i=0;i<strArr.length;i++){
                if(strArr[i].length()>str.length()){
                    list.clear();//当前串大于原最大串,先清除list。再将串添加到集合
                    str=strArr[i];
                    list.add(strArr[i]);
                }else if(strArr[i].length()==str.length()){
                    list.add(strArr[i]);
                }
            }
            for(String s:list){
                System.out.print(s);
            }
            System.out.println(","+list.get(list.size()-1).length());
        }
    }
}

发表于 2023-02-08 09:36:11 回复(0)
正则加自定义排序
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNextLine()){
            String str = in.nextLine();
            String[] newstr = str.split("[^0-9]+");   //正则
            Arrays.sort(newstr,new Comparator<String>(){    //自定义排序
                @Override
                public int compare(String o1,String o2){
                    return o2.length()-o1.length();
                }
            });
            String result="";
            for(int i=0;i<newstr.length;i++){
                if(newstr[i].length()==newstr[0].length())
                result+=newstr[i];
            }
            System.out.println(result+","+newstr[0].length());
        }
    }
}


发表于 2022-12-21 23:43:19 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {         
            String s = in.nextLine();
            f(s);
        }
    }
    private static void f(String s){
        String[] a = s.split("[^0-9]+");
            int[] l = new int[a.length];
            for (int i = 0; i < a.length; i++){
                l[i] = a[i].length();
            }
            int max = 0;
            for (int i = 0; i < a.length; i++){
                if (l[i] > max){
                    max = l[i];
                };
            }
            for (int i = 0; i < a.length; i++){
                if (a[i].length() == max){
                    System.out.print(a[i]);
                }
            }
            System.out.print("," + max);
            System.out.println();
    }
}

发表于 2022-11-03 22:26:28 回复(0)

import java.io.*;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
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 len = str.length();
            int maxLen = 0;
            //因为可能会有多个结果,所以采用list存储数据
            List<String> list = new ArrayList<>();
            for (int i = 0; i < len; i++) {
                //遇到非数字字符,直接下一次
                if (str.charAt(i) < 48 || str.charAt(i) > 57) {
                    continue;
                }
                int curLen = maxLen(str, i);
                //截取数字字符串
                String subStr = str.substring(i, i + curLen);
                if (curLen > maxLen) {
                    maxLen = curLen;
                    //当前的长度更大时,需要清空之前存储的数据,直接new一个
                    list = new ArrayList<>();
                    list.add(subStr);
                } else if (curLen == maxLen) {
                    //长度相等情况下,全部存起来
                    list.add(subStr);
                }
                //因为i到i+curLen之间一定为数字,且i+curLen+1一定不是数字。中间的不需要再次进入循环
                i += curLen;
            }
            for (String s : list) {
                System.out.print(s);
            }
            System.out.println("," + maxLen);
        }
    }
    // 从start位置开始,可以得到的最大连续数字序列长度
    public static int maxLen (String s, int start) {
        int i = start + 1; //定义在外面是后面需要用i取len
        for (; i < s.length(); i++) {
            //当遇到非数字字符时,跳出循环
            if (s.charAt(i) < 48 || s.charAt(i) > 57) {
                break;
            }
        }
        //跳出循环时候 i 超出length或者非数字,start与i直接一定是数字
        return i - start; 
    }
}


发表于 2022-09-30 11:15:51 回复(0)
import java.util.Scanner;
//应该是最短的了
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()) {
            String[] ints = in.nextLine().split("[^0-9+]");
            int maxLength = 0;
            for(String i: ints){
                maxLength = Math.max(maxLength, i.length());
            }

            for(String i: ints){
                if(i.length() == maxLength){
                    System.out.print(i);
                }
            }
            System.out.println(","+maxLength);
        }
    }
}

发表于 2022-09-20 18:39:37 回复(2)