Untitled

 avatar
unknown
plain_text
12 days ago
2.4 kB
2
Indexable
class Trie {
    Trie[] links;
    boolean flag;
    public Trie() {
        links = new Trie[26];
        flag = false;
    }
    public boolean containsKey(char ch) {
        return links[ch - 'a'] != null;
    }
    public Trie get(char ch) {
        return links[ch - 'a'];
    }
    public void put(char ch, Trie Trie) {
        links[ch - 'a'] = Trie;
    }
    public void setEnd() {
        flag = true;
    }
    public boolean isEnd() {
        return flag;
    }
}
class TrieOperations {
    private Trie root;
    public TrieOperations() {
        root = new Trie();
    }
    public void insert(String word) {
        Trie temp = root;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (!temp.containsKey(ch)) {
                temp.put(ch, new Trie());
            }
            temp = temp.get(ch);
        }
        temp.setEnd();
    }
    public boolean checkIfAllPrefixExists(String word) {
        Trie temp = root;
        boolean flag = true;
        for (int i = 0; i < word.length() && flag; i++) {
            char ch = word.charAt(i);
            if (temp.containsKey(ch)) {
                temp = temp.get(ch);
                if(temp.isEnd() == false)
                   return false;
            } else {
                return false;
            }
        }
        return true;
    }
}
public class Main {
    public static String completeString(int n, String[] a) {
        Trie obj = new Trie();
        for (String word : a)
            obj.insert(word);
        String longest = "";
        for (String word : a) {
            if (obj.checkIfAllPrefixExists(word)) {
                if (word.length() > longest.length()
                        || (word.length() == longest.length()
                                && word.compareTo(longest) < 0)) {
                    longest = word;
                }
            }
        }
        if (longest.equals("")) return "None";
        return longest;
    }
    public static void main(String[] args) {
        String[] strings = {"striver", "strive", "striving",
                                "striven", "strived", "striv"};
        String longestComplete = completeString(strings.length, strings);
        System.out.println("Longest complete string: " + longestComplete);
    }
}
Leave a Comment