清晰!遍历一遍获取长度最大值+正则匹配判断,时间复杂度O(n)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String string = sc.nextLine();
doSearch(string);
}
}
public static void doSearch(String string){
int n = 0,maxOne = 0;//计数变量
// 遍历一遍获取长度最大值,时间复杂度O(n)
for(int i=0; i < string.length(); i++){
if(Character.isDigit(string.charAt(i))){
n++;
maxOne = Integer.max(maxOne,n);
}else{
n = 0;
}
}
// 再遍历一遍获取长度为最大值的子串,并判断子串中是否全是数字,时间复杂度O(n)
StringBuilder sb = new StringBuilder();
for(int i = 0; i <= string.length() - maxOne; i ++){
String str = string.substring(i, i + maxOne);
if(0 == str.replaceAll("[0-9]", "").length())){
sb.append(str);
}
}
System.out.println(sb+","+ maxOne);
}
}