Cod sursa(job #2022873)

Utilizator dan.ghitaDan Ghita dan.ghita Data 17 septembrie 2017 16:03:37
Problema Trie Scor 100
Compilator java Status done
Runda Arhiva educationala Marime 2.55 kb
import java.io.*;
import java.util.HashMap;

class TrieNode {
    private HashMap<Character, TrieNode> next = new HashMap<>();
    private int count = 0;

    void insert(String word, int charIndex) {
        Character key = word.charAt(charIndex);

        if(!next.containsKey(key))
            next.put(key, new TrieNode());

        if(charIndex < word.length() - 1)
            next.get(key).insert(word, charIndex + 1);
        else
            ++next.get(key).count;
    }

    void delete(String word, int charIndex) {
        Character key = word.charAt(charIndex);

        if(!next.containsKey(key)) return;

        if(charIndex == word.length() - 1)
            --next.get(key).count;
        else
            next.get(key).delete(word, charIndex + 1);

        if(next.get(key).isRedundant())
            next.remove(key);
    }

    int count(String word, int charIndex) {
        Character key = word.charAt(charIndex);

        if(!next.containsKey(key))
            return 0;

        if(charIndex == word.length() - 1)
            return next.get(key).count;
        else
            return next.get(key).count(word, charIndex + 1);
    }

    int prefix(String word, int charIndex) {
        Character key = word.charAt(charIndex);

        if(!next.containsKey(key))
            return charIndex;

        if(charIndex == word.length() - 1)
            return charIndex + 1;
        else
            return Math.max(next.get(key).prefix(word, charIndex + 1), next.size() > 1 ? charIndex : 0);
    }

    private boolean isRedundant() {
        return count <= 0 && !hasNext();
    }

    private boolean hasNext() {
        return !next.isEmpty();
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("trie.in"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("trie.out"));

        TrieNode trieRoot = new TrieNode();

        String line;
        while((line = br.readLine()) != null) {
            String word = line.substring(2);
            switch (line.charAt(0)) {
                case '0':
                    trieRoot.insert(word, 0);
                    break;
                case '1':
                    trieRoot.delete(word, 0);
                    break;
                case '2':
                    bw.write(trieRoot.count(word, 0) + "\n");
                    break;
                case '3':
                    bw.write(trieRoot.prefix(word, 0) + "\n");
                    break;
            }
        }

        br.close();
        bw.close();
    }
}