题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec?tpId=37&tqId=21315&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D2%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
不用正则表达式的方法,快慢指针遍历法
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String str = sc.nextLine(); int j=0, strLength = 0; ArrayList<String> list = new ArrayList<String>();//结果集 for (int i = 0 ; i < str.length(); i++) { for (j = i; j < str.length(); j++) { if (Character.isDigit(str.charAt(j))) break; } //这个循环找到数字开始的位置 i = j; for (j = i; j < str.length(); j++) { if (!Character.isDigit(str.charAt(j))) break; } //这个循环找到数字结束的位置 if(strLength < (j - i)){ strLength=j-i; list.clear(); list.add(str.substring(i, j)); } //有更长的数字串则清空list再加入,没有则直接加入 else if(strLength == (j - i)) list.add(str.substring(i, j)); i = j; } System.out.println(arrListToString(list) + "," + strLength); } } public static String arrListToString(ArrayList<String> list){ String str=""; for(String s:list){ str+=s; } return str; } }