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

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

https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\n");
        while (scanner.hasNext()) {
            String S = scanner.next();
            int max = 0;
            int left=0,right=0;
            HashMap<Integer, Integer> hashMap = new HashMap<>();
            while (left<S.length()) {
                if (Character.isDigit(S.charAt(left))) {
                    right = left;
                    while (right<S.length()) {
                        if (!Character.isDigit(S.charAt(right))) {
                            break;
                        }
                        right++;
                    }
                    right--;
                    if (max<=right-left+1) {
                        max = right-left+1;
                        hashMap.put(left, max);
                    }
                    left=right;
                }
                left++;
            }

            Integer value = hashMap.entrySet().stream().max(Map.Entry.comparingByValue()).get().getValue();
            for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
                if (Objects.equals(entry.getValue(), value)) {
                    System.out.print(S.substring(entry.getKey(), entry.getKey()+value));
                }
            }
            System.out.print(","+value+"\r\n");
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务