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

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

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

import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String nextLine = in.nextLine();
            if (Objects.isNull(nextLine) || nextLine.equals("")) {
                break;
            }
            String regex = "[0-9]+";
            Pattern compile = Pattern.compile(regex);
            Matcher matcher = compile.matcher(nextLine);
            List<String> numList = new ArrayList<>();
            while (matcher.find()) {
                numList.add(matcher.group());
            }
            List<SimpleEntry<String, Integer>> entries = numList.stream()
                .map(item -> new SimpleEntry<>(item, item.length()))
                .collect(Collectors.toList());
            Integer max = entries.stream()
                .map(SimpleEntry::getValue)
                .max(Comparator.comparingInt(Integer::intValue))
                .orElse(0);
            String collect = entries.stream()
                .sorted((o1, o2) -> o2.getValue() - o1.getValue())
                .filter(item -> item.getValue()
                    .equals(max))
                .map(item -> "" + item.getKey())
                .collect(Collectors.joining(""));
            System.out.println(collect + "," + max);
        }
    }
}

全部评论

相关推荐

11-03 18:50
门头沟学院 Java
迷茫的大四🐶:问就是马上到,一周五天,6个月以上,全国可飞
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务