String中找最长数字串(java)
在字符串中找出连续最长的数字串
http://www.nowcoder.com/questionTerminal/2c81f88ecd5a4cc395b5308a99afbbec
java
技巧:在最后加一个字符
import java.util.*; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); while(in.hasNext()){ String s = in.nextLine(); s += "e"; LinkedList<String> list = new LinkedList<>(); int curLen = 0; int max = 0; StringBuilder sb = new StringBuilder(); for (int p1 = 0; p1 < s.length(); p1++){ char cc = s.charAt(p1); if (isNumber(cc)){ curLen++; sb.append(s.charAt(p1)); }else if (!isNumber(s.charAt(p1)) && curLen != 0){ if (curLen == max){ list.add(sb.toString()); }else if (curLen > max){ list.clear(); list.add(sb.toString()); max = curLen; } curLen = 0; sb = new StringBuilder(); } } String output = ""; for (int i = 0; i < list.size(); i++){ output += list.get(i); } output += ","; output += max; System.out.println(output); } } private static boolean isNumber(char c){ return c >= '0' && c <= '9'; } }
把非数字全部变成'a'
按a分割
String[] strs=str1.split("a");