简体   繁体   中英

How can I speed up my stream().filter() logic?

I'm currently doing this Kattis problem: https://open.kattis.com/problems/bing

The input can consist of up to 100k lines, meaning my stream-logic needs speed.

For each incoming line I want to do some stream evaluation. Firstly filtering on first char, to mitigate the check towards the totally mismatching words.. Then checking the full word on the remaining list.

However, the challenges' time limit of 1 sec is not reached.. Are there other ways of filtering making the logic faster? Or any other ways of optimizing?

import java.util.ArrayList;
import java.util.Scanner;

public class Bing {
    private static String word;
    private static Long count;
    static ArrayList<String> checked = new ArrayList<>();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();

        for (int i = 0; i < N; i++) {
            word = sc.next();
            count = checked.stream()
                    .filter(c-> c.startsWith(String.valueOf(word.charAt(0))))
                    .filter(c-> c.startsWith(word))
                    .count();

            System.out.println(count);
            checked.add(word);
        }
    }
} 

I found a solid Java implementation of the node trie on same kattis question: https://github.com/minidomo/Kattis/blob/master/Java/bing.java

Yes, there's an optimization - you can use Trie data structure instead of the List.

You may find it useful: https://www.geeksforgeeks.org/count-the-number-of-words-with-given-prefix-using-trie/ (It's in C++/Phyton though)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM