题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine();
System.out.println(maxNum(str));
}
}
private static String maxNum(String str) {
//使用空格替换所有的字符,仅留下数字
String s = str.replaceAll("[A-Za-z]"," ");
//根据空格拆分出数字串
String[] split = s.split(" ");
String max = "";
StringBuilder sb = new StringBuilder();
for (String value: split) {
//找到最长的数字串
if(value.length() > max.length()){
max = value;
//将max保存到sb中
sb = new StringBuilder(max);
}//数字串长度相等,就直接保存到sb中
else if (value.length() == max.length()){
sb.append(value);
}
}
//最后保存逗号和最长数字串的长度
sb.append(",").append(max.length());
return sb.toString();
}
}
上海得物信息集团有限公司公司福利 1254人发布