题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
http://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
while((str = br.readLine()) != null){
// 输出结果
System.out.println(longestNum(str));
}
}
private static String longestNum(String str){
String s = str;
// 创建StringBuilder对象用于保存结果
StringBuilder sb = new StringBuilder();
int i = 0,maxLen = 0;
while(i < str.length()){
int j = i;
// 遇到数字开始while循环
while(i < str.length() && Character.isDigit(str.charAt(i))){
i++;
}
if(i - j == maxLen){
sb.append(s.substring(j,i));
}
if(i - j > maxLen){
maxLen = i - j;
sb = new StringBuilder(s.substring(j,i));
}
i++;
}
return sb.append("," + maxLen).toString();
}
}