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

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

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

import java.util.Scanner;

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String str = in.nextLine();
            int length = 0;
            String temp = "";
            Map<String, Integer> map = new LinkedHashMap<>();
            for (int i = 0; i < str.length(); i++) {
                if (Character.isDigit(str.charAt(i))) {
                    length++;
                    temp += str.charAt(i);
                } else {
                    map.put(temp, length);
                    length = 0;
                    temp = "";
                }
            }
            map.put(temp, length);
            Collection<Integer> values = map.values();
            int max = Collections.max(values);
            StringBuilder sb = new StringBuilder();
            for (String key : map.keySet()) {
                if (map.get(key) == max) {
                    sb.append(key);
                }
            }
            System.out.println(sb + "," + max);
        }
    }
}

这道题不难,就是输出的要求有点恶心,得将max相同的多个字符串拼在一起输出,而且要保证其是按照原字符串的排列顺序,所以在用map的时候得用LinkedHashMap解决。

全部评论

相关推荐

不愿透露姓名的神秘牛友
08-09 12:05
点赞 评论 收藏
分享
彧未sr:查看图片
投递牧原集团等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务