题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
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);
}
}
}

