题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
笨办法,还有优化的空间
import java.util.*;
import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) throws IOException {
// Scanner in = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
// 注意 hasNext 和 hasNextLine 的区别
while ((str = br.readLine()) != null) { // 注意 while 处理多个 case
char[] c = str.toCharArray();
int length = 0;
int maxLength = 0;
ArrayList<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
// if (i == str.length()-1 && Character.isDigit(c[i])) {
if (c[i] >= '0' && c[i] <= '9' && i == str.length() - 1) {
length++;
sb.append(c[i]);
maxLength = (maxLength > length) ? maxLength : length;
if (sb.length() == maxLength) {
list.add(sb.toString());
}
// } else if (Character.isDigit(c[i])) {
} else if (c[i] >= '0' && c[i] <= '9') {
length++;
sb.append(c[i]);
maxLength = (maxLength > length) ? maxLength : length;
} else {
length = 0;
if (sb.length() > 0)
list.add(sb.toString());
sb.setLength(0);
}
}
for (String s : list) {
if (s.length() == maxLength)
System.out.print(s);
}
System.out.println("," + maxLength);
}
}
}
查看11道真题和解析