classTrie { Trie *child[26]; bool isWord; public: /** Initialize your data structure here. */ Trie() { isWord=false; for (int i=0; i<26; ++i) child[i]=nullptr; } /** Inserts a word into the trie. */ voidinsert(stringword){ Trie *t=this; for (char c:word) { if (!t->child[c-'a']) { t->child[c-'a']=new Trie(); } t=t->child[c-'a']; } t->isWord=true; } /** Returns if the word is in the trie. */ boolsearch(stringword){ Trie *t=this; for (char c:word) { if (!t->child[c-'a']) { returnfalse; } t=t->child[c-'a']; } return t->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ Trie *t=this; for (char c:prefix) { if (!t->child[c-'a']) { returnfalse; } t=t->child[c-'a']; } returntrue; } };
/** * 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); */
classTrie { Trie *child[26]; bool isWord; public: /** Initialize your data structure here. */ Trie() { isWord=false; for (int i=0; i<26; ++i) child[i]=nullptr; } /** Inserts a word into the trie. */ voidinsert(stringword){ Trie *t=this; for (char c:word) { if (!t->child[c-'a']) { t->child[c-'a']=new Trie(); } t=t->child[c-'a']; } t->isWord=true; } /** Returns if the word is in the trie. */ boolsearch(stringword){ Trie *t=this; for (char c:word) { if (!t->child[c-'a']) { returnfalse; } t=t->child[c-'a']; } return t->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ Trie *t=this; for (char c:prefix) { if (!t->child[c-'a']) { returnfalse; } t=t->child[c-'a']; } returntrue; }
/* 判断当前这个节点是否是整个树的前缀,也就是孩子只有一个字母 */ charisPrefixNode(){ Trie *t=this; int cnt=0; char c='\0'; for (int i=0; i<26; ++i) { if (t->child[i] != nullptr) { c=(char) ('a'+i); ++cnt; } if (cnt>1) break; } return cnt==1?c:'\0'; }
stringsearchMaxPrefix(){ string res=""; Trie *t=this; char c = t->isPrefixNode(); while (!t->isWord && c!='\0') { res+=c; t=t->child[c-'a']; c=t->isPrefixNode(); } return res; } }; classSolution { public: stringlongestCommonPrefix(vector<string>& strs){ Trie *root = new Trie(); for (auto str:strs) { if (str=="") return""; root->insert(str); } return root->searchMaxPrefix(); } };