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

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

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

Life is short, you need Stream

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<String> list = new ArrayList<String>();
        while (in.hasNextLine()) {
            String[] strs = in.nextLine().split("[^0-9]+");
            final int max =  Arrays.stream(strs)
                             .max(Comparator.comparingInt(String::length)).get().length();
            Arrays.stream(strs).filter(x -> x.length() == max).forEach(System.out::print);
            System.out.println("," + max);
        }
    }
}

模拟

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<String> list = new ArrayList<String>();
        while (in.hasNextLine()) {
            System.out.println(longestDigitSubstring(in.nextLine(), list));
        }
    }

    static String longestDigitSubstring(String s, List<String> list) {
        boolean flag = false;
        int max = 0;
        for (int i = 0, k = 0; i < s.length(); i++) {
            // 遇到数字且数字子串还没开始 则标记数字子串开始及开始的下标
            if (Character.isDigit(s.charAt(i)) && !flag) {
                k = i;
                flag = true;
            }
            // 如果遇到字母且数字子串已经开始 则标记数字子串结束 并将子串记录
            if (Character.isLetter(s.charAt(i)) && flag) {
                list.add(s.substring(k, i));
                max = Math.max(max, i - k);
                flag = false;
            }
            // 走到最后
            if (i == s.length() - 1 && Character.isDigit(s.charAt(i))) {
                list.add(s.substring(k));
                max = Math.max(max, s.length() - k);
            }
        }
        final int m = max;
        StringBuilder sb = new StringBuilder();
        sb.append(list.stream()
                  .filter(x -> x.length() == m)
                  .reduce((x, y) -> x + y)
                  .orElse(null));
        list.clear();
        return sb.append(",").append(max).toString();
    }
}
#华为笔试#
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:52
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务