1. 常规思路
遍历一次,和之前的数字字符串比较长度,找到最长的
1 /** 2 * @param str 输入的字符串 3 */ 4 public void getLongestNumString(String str) { 5 char[] arr = str.toCharArray(); 6 StringBuilder tmp = new StringBuilder(); 7 String ret = ""; 8 List<String> list = new ArrayList<>(); 9 boolean isConsecutive = false; 10 for (char ch : arr) { 11 if (Character.isDigit(ch)) { 12 if (!isConsecutive) { 13 tmp = new StringBuilder(); 14 } 15 tmp.append(ch); 16 isConsecutive = true; 17 if (ret.length() < tmp.toString().length()) { 18 ret = tmp.toString(); 19 list.clear(); 20 list.add(ret); 21 } else if (ret.length() == tmp.toString().length()) { 22 list.add(tmp.toString()); 23 } 24 } else { 25 isConsecutive = false; 26 } 27 } 28 29 for (String string : list) { 30 System.out.print(string); 31 } 32 System.out.print(","+ret.length()); 33 System.out.println(); 34 }
2. 其他思路
来源:https://www.nowcoder.com/questionTerminal/2c81f88ecd5a4cc395b5308a99afbbec?f=discussion 哎呀哎呀123 的回答
(利用正则表达式)将所有非数字的字符转换成一个字母,然后按照这个字母进行分隔,最后找到最长的数字串
1 /** 2 * private static final String REPLACE_LETTER = "a"; 3 * 4 * @param str 输入的字符串 5 */ 6 public void getLongestNumString(String str) { 7 if (str == null || str.length() == 0) { 8 System.out.println(0); 9 return; 10 } 11 12 str = str.replaceAll("\D+", REPLACE_LETTER); 13 String[] arr = str.split(REPLACE_LETTER); 14 15 int maxLength = -1; 16 for (String tmp : arr) { 17 if (tmp.length() > maxLength) { 18 maxLength = tmp.length(); 19 } 20 } 21 22 for (String tmp : arr) { 23 if (tmp.length() == maxLength) { 24 System.out.print(tmp); 25 } 26 } 27 28 System.out.println("," + maxLength); 29 }