题解 | #字符串中找出连续最长的数字串#

字符串中找出连续最长的数字串

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));

            }
        }

    }


#字节测试开发一面面经#
全部评论

相关推荐

09-29 17:44
已编辑
蔚来_测(准入职员工)
//鲨鱼辣椒:见不了了我实习了四个月上周再投筛选了一天就给我挂了
点赞 评论 收藏
分享
totoroyyw:千年老妖😂
投递华为等公司10个岗位
点赞 评论 收藏
分享
点赞 1 评论
分享
牛客网
牛客企业服务