Simple and Neat Java code


  • 0
    T

    """
    public class WordDictionary {

    class TrieNode{
        char c;
        String word;
        TrieNode[] childs;
        TrieNode(char c){
            this.c = c;
            childs = new TrieNode[26];
        }
    }
    private TrieNode root = new TrieNode(' ');
    // Adds a word into the data structure.
    public void addWord(String word) {
        TrieNode temp = root;
        for(int i = 0; i < word.length(); i++){
            int index = word.charAt(i) - 'a';
            if(temp.childs[index] == null)
                temp.childs[index] = new TrieNode(word.charAt(i));
            temp = temp.childs[index];
        }
        temp.word = word;
    }
    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    public boolean search(String word) {
        return processWildcard(word,root);
    }
    private boolean processWildcard(String word,TrieNode root){
        if(word.equals(""))
            return root.word != null;
        TrieNode temp = root;
        char c = word.charAt(0);
        if(c == '.'){
            boolean flag = false;
            for(int i = 0; i < 26; i++){
                if(temp.childs[i] != null)
                    flag |= processWildcard(word.substring(1),root.childs[i]);
            }
            return flag;
        }
        else
            return root.childs[c - 'a'] == null ? false : processWildcard(word.substring(1),root.childs[c - 'a']);
    }
    

    }
    """
    // Your WordDictionary object will be instantiated and called as such:
    // WordDictionary wordDictionary = new WordDictionary();
    // wordDictionary.addWord("word");
    // wordDictionary.search("pattern");


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.