Tuesday, October 20, 2015

[leetcode]Add and Search Word - Data structure design

这题就是 在Implement Trie (Prefix Tree) 基础上 加个DFS
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
public class WordDictionary {
    TrieNode root = new TrieNode();
    // Adds a word into the data structure.
    public void addWord(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++){
            char temp = word.charAt(i);
            if (!node.hasChild(temp)){
                node.addChild(temp);
            }
            node = node.getChild(temp);
        }
        node.setNodeAWordEnd();
    }

    // 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 dfs(word, root, 0);
    }

    private boolean dfs(String word, TrieNode root, int currentIndex){
        if (currentIndex == word.length()){
            return root.isNodeWordEnd();
        }
        char currentChar = word.charAt(currentIndex);
        if (root.hasChild(currentChar)){
            return dfs(word, root.getChild(currentChar), currentIndex+1);
        }

        if (currentChar == '.'){
            Iterator<TrieNode> listOfChildren = root.getChildren().values().iterator();
            while (listOfChildren.hasNext()){
                if (dfs(word, listOfChildren.next(), currentIndex+1)){
                    return true;
                }
            }
        }

        return false;
    }
}


class TrieNode {
    HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
    boolean isWord = false;
    char currentChar;

    public TrieNode() {
        
    }

    public TrieNode(char in){
        currentChar = in;
    }

    public void addChild(char kid){
        if (children.containsKey(kid)){
            return;
        }
        children.put(kid, new TrieNode(kid));
    }


    public boolean hasChild(char kid){
        return children.containsKey(kid);
    }

    public TrieNode getChild(char kid){
        if (!hasChild(kid)){
            return null;
        }
        return children.get(kid);
    }

    public boolean isNodeWordEnd(){
        return isWord;
    }
    
    public void setNodeAWordEnd(){
        isWord = true;
    }
    
    public HashMap<Character, TrieNode> getChildren(){
        return children;
    }
}

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

No comments:

Post a Comment