zoukankan      html  css  js  c++  java
  • HackerRank "No Prefix Set"

    Typical Trie usage. But please note that it could be any order of input strings.

    #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;
    }
    View Code
  • 相关阅读:
    大数据
    优化
    gnu
    sed
    hadoop部署
    安装 zookeeper
    ansible
    ssh 配置无密码登录
    未完待续
    解正向代理、反向代理、透明代理
  • 原文地址:https://www.cnblogs.com/tonix/p/4850586.html
Copyright © 2011-2022 走看看