题解 | #字符串中找出连续最长的数字串#
字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/bd891093881d4ddf9e56e7cc8416562d
#字节测试开发一面面经#public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String w = sc.nextLine(); List<Map<String,Integer>> list = new ArrayList<>(); char[] arr = w.toCharArray(); //连续index start int start = -1; //连续index end int end = -1; for(int i = 0;i<arr.length-1;i++){ int be = Integer.valueOf(arr[i]); int ne = Integer.valueOf(arr[i+1]); if((be+1)==ne){ //初始连续 if (start==-1){ start = i; } //结尾处字符串连续 if (i==arr.length-2){ end = i+1; Map<String,Integer> map = new HashMap<>(); //连续index start map.put("start",start); //连续index end map.put("end",end); //start至end间隔 map.put("abs",end-start+1); list.add(map); } } else { //连续结束 if (start!=-1){ end = i; Map<String,Integer> map = new HashMap<>(); //连续index start map.put("start",start); //连续index end map.put("end",end); //start至end间隔 map.put("abs",end-start+1); list.add(map); } //不连续保证index为初始状态 start = -1; end = -1; } } if (list.size()>0){ //根据abs(start至end间隔)排序 list.sort(Comparator.comparing(a -> a.get("abs"))); //取间隔最大 Map<String, Integer> map = list.get(list.size() - 1); Integer start1 = map.get("start"); Integer end1 = map.get("end"); System.out.println(w.substring(start1,end1+1)); } } }