题解 | 在字符串中找出连续最长的数字串
在字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
import java.util.Scanner;
// 注意类名必须为 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 l = in.nextLine();
// String[] lines = l.split("[a-z]");
// int max = 0;
// int[] index = new int[lines.length];
// for (int i = 0; i < lines.length; i ++) {
// index[i] = lines[i].length();
// max = Math.max(index[i], max);
// }
// for (int i = 0; i < lines.length; i ++) {
// if (index[i] == max) {
// System.out.print(lines[i]);
// }
// }
// System.out.print("," + max);
int[] dp = new int [l.length() + 1];
int max = 0;
for (int i = 1; i <= l.length(); i++) {
if (Character.isDigit(l.charAt(i-1))) {
dp[i] = dp[i - 1] + 1;
if (dp[i] > max) {
max = dp[i];
}
} else {
dp[i] = 0;
}
}
for (int i = 1; i < l.length()+1; i++) {
if (max == dp[i]) {
System.out.print(l.substring(i - max, i));
}
}
System.out.print("," + max);
}
}
}


查看17道真题和解析