题意:实现Trie
class TrieNode{ public: bool isword; TrieNode* nex[26]; TrieNode():isword(false){ for(int i = 0; i < 26; ++i) nex[i] = NULL; } }; class Trie { public: TrieNode *root; /** Initialize your data structure here. */ Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ void insert(string word) { TrieNode *p = root; int len = word.size(); for(int i = 0; i < len; ++i){ if(p -> nex[word[i] - 'a'] == NULL){ p -> nex[word[i] - 'a'] = new TrieNode(); } p = p -> nex[word[i] - 'a']; } p -> isword = true; } /** Returns if the word is in the trie. */ bool search(string word) { TrieNode *p = root; int len = word.size(); for(int i = 0; i < len; ++i){ if(p -> nex[word[i] - 'a'] == NULL) return false; p = p -> nex[word[i] - 'a']; } return p -> isword; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { TrieNode *p = root; int len = prefix.size(); for(int i = 0; i < len; ++i){ if(p -> nex[prefix[i] - 'a'] == NULL) return false; p = p -> nex[prefix[i] - 'a']; } return true; } }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */