Typical Trie usage. But please note that it could be any order of input strings.
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include <algorithm> #include <string> #include <vector> #include <queue> #include <unordered_map> #include <unordered_set> #include <iostream> using namespace std; class TrieNode { public: // Initialize your data structure here. TrieNode() { c = 0; bIsLast = false; } TrieNode(char vc) { c = vc; bIsLast = false; } public: char c; bool bIsLast; unordered_map<char, TrieNode*> childMap; }; class Trie { public: Trie() { root = new TrieNode(); } ~Trie() { if (root) { for(auto kv : root->childMap) { delete kv.second; } delete root; } } // Inserts a word into the trie. bool insert(string s) { TrieNode *r = root; for (int i = 0; i < s.length(); i++) { if (r->childMap.find(s[i]) == r->childMap.end()) { r->childMap.insert(make_pair(s[i], new TrieNode(s[i]))); } else if (r->childMap[s[i]]->bIsLast) { return false; } r = r->childMap[s[i]]; } r->bIsLast = true; return r->childMap.empty(); } private: TrieNode* root; }; int main() { Trie tr; int n; cin >> n; vector<string> strs; while(n --) { string str; cin >> str; if(!tr.insert(str)) { cout << "BAD SET" << endl; cout << str << endl; return 0; } } cout << "GOOD SET" << endl; return 0; }