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

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

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

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.hasNextLine()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            List<String> longestSubstrings = findLongestNumericSubstrings(a);
            if (longestSubstrings.isEmpty()) {
                System.out.println("没有数字子串");
            } else {
                int maxLength = longestSubstrings.get(0).length();
                for (String substring : longestSubstrings) {
                    if (substring.length() == maxLength) {
                        System.out.print(substring);
                    }
                }
                System.out.println("," + maxLength);
            }
        }
    }


    private static List<String> findLongestNumericSubstrings(String input) {
        List<String> substrings = new ArrayList<>();
        int maxLength = 0;
        int start = -1;
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (Character.isDigit(ch)) {
                if (start == -1) {
                    start = i;
                }
            } else {
                if (start != -1) {
                    String substring = input.substring(start, i);
                    if (substring.length() > maxLength) {
                        maxLength = substring.length();
                        substrings.clear();
                        substrings.add(substring);
                    } else if (substring.length() == maxLength) {
                        substrings.add(substring);
                    }
                    start = -1;
                }
            }
        }
        // Check for the last substring if it ends with a digit
        if (start != -1) {
            String substring = input.substring(start);
            if (substring.length() > maxLength) {
                maxLength = substring.length();
                substrings.clear();
                substrings.add(substring);
            } else if (substring.length() == maxLength) {
                substrings.add(substring);
            }
        }
        return substrings;
    }


}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务