Add and Search Word - Data structure design

来源:互联网 发布:泰国4g网络制式 频段 编辑:程序博客网 时间:2024/05/01 21:39

参照,trie的实现。

好了,可以先去上课了。

public class WordDictionary {    private TrieNode root;    public WordDictionary() {        root = new TrieNode();    }    // Adds a word into the data structure.    public void addWord(String word) {        if (word == null || word.length() == 0) {            return;        }        TrieNode cur = root;        for (int i = 0; i < word.length(); i++) {            int num = word.charAt(i) - 'a';            if (cur.children[num] == null) {                cur.children[num] = new TrieNode();            }            cur = cur.children[num];        }        cur.isExisted = true;    }    // 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 searchHelper(word, root, 0);    }        private boolean searchHelper(String word, TrieNode node, int pos) {        if (node == null) {            return false;        }        if (node.isExisted && pos == word.length()) {            return true;        }        if (pos >= word.length()) {            return false;        }        char c = word.charAt(pos);        if (c == '.') {            for (TrieNode childNode: node.children) {                if (searchHelper(word, childNode, pos + 1) ) {                    return true;                   }            }        } else {            int num = c - 'a';            if (node.children[num] != null) {                return searchHelper(word, node.children[num], pos + 1);            }        }                return false;    }        private class TrieNode {        TrieNode[] children = new TrieNode[26];        boolean isExisted;        public TrieNode() {}    }}// Your WordDictionary object will be instantiated and called as such:// WordDictionary wordDictionary = new WordDictionary();// wordDictionary.addWord("word");// wordDictionary.search("pattern");



0 0