题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
http://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
简单哩。
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static String getLongestDigitStr(String str) {
int max = 0;
char[] cs = str.toCharArray();
Map<String, Integer> sm = new LinkedHashMap<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cs.length; i++) {
int t = 0;
sb.setLength(0);
for (int j = i; j < cs.length && cs[j] <= '9' && cs[j] >= '0'; j++) {
sb.append(cs[j]);
t++;
}
if (max <= t){
max = t;
sm.put(sb.toString(), max);
}
}
sb.setLength(0);
for (String s : sm.keySet()) {
if (sm.get(s) == max){
sb.append(s);
}
}
return sb+","+max;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.next();
System.out.println(getLongestDigitStr(str));
}
}
}