题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
http://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
char[] chrs = str.toCharArray();
process(chrs, str);
}
}
public static void process(char[] chrs, String str) {
ArrayList<String> ans = new ArrayList<>();
int acc = 0;
int start = 0;
int sign = 0;
for (int i = 0; i < chrs.length; i++) {
char chr = chrs[i];
if (chr >= '0' && chr <= '9') {
if (sign == 0) {
sign = 1;
start = i;
}
} else {
if (sign == 1) {
sign = 0;
if (acc == i - start) {
ans.add(str.substring(start, i));
} else if (acc < i - start) {
ans.clear();
ans.add(str.substring(start, i));
acc = i - start;
}
}
}
}
if (sign == 1) {
if (acc == chrs.length - start) {
ans.add(str.substring(start));
} else if (acc < chrs.length - start) {
ans.clear();
ans.add(str.substring(start));
}
}
for (String tmp : ans) {
System.out.print(tmp);
}
System.out.println("," + ans.get(0).length());
}
}