📌  相关文章
📜  检查给定的Trie是否包含每个字母开头的单词

📅  最后修改于: 2021-04-17 10:41:22             🧑  作者: Mango

给定一个Trie,任务是检查它是否包含从[a – z]的每个字母开始的单词。

例子:

方法:我们只需要关注给定Trie的根节点,而无需遍历其他节点。我们只是简单地检查Trie是否具有所有指向有效节点的子指针,即从字母表的每个字符开始都有单词。

下面是上述方法的实现:

// C++ implementation of the approach
#include 
using namespace std;
  
const int ALPHABET_SIZE = 26;
  
// Trie node
struct TrieNode {
    struct TrieNode* children[ALPHABET_SIZE];
  
    // isEndOfWord is true if the node represents
    // end of a word
    bool isEndOfWord;
};
  
// Returns new trie node (initialized to NULL)
struct TrieNode* getNode(void)
{
    struct TrieNode* pNode = new TrieNode;
  
    pNode->isEndOfWord = false;
  
    for (int i = 0; i < ALPHABET_SIZE; i++)
        pNode->children[i] = NULL;
  
    return pNode;
}
  
// If not present, inserts key into trie
// If the key is prefix of trie node, just
// marks leaf node
void insert(struct TrieNode* root, string key)
{
    struct TrieNode* pCrawl = root;
  
    for (int i = 0; i < key.length(); i++) {
        int index = key[i] - 'a';
        if (!pCrawl->children[index])
            pCrawl->children[index] = getNode();
  
        pCrawl = pCrawl->children[index];
    }
  
    // Mark last node as leaf
    pCrawl->isEndOfWord = true;
}
  
// Function to check if Trie contains words
// starting from all the alphabets
bool containsAll(TrieNode* root)
{
    // We check if root node has all childs
    // if None of them is NULL then we return true
    for (int i = 0; i < 26; i++) {
  
        // If there is no word in the trie starting
        // from the current alphabet
        if (root->children[i] == NULL)
            return false;
    }
    return true;
}
  
// Driver code
int main()
{
  
    string keys[] = { "element", "fog", "great", "hi", "ok",
                      "ios", "parrot", "quiz", "kim", "mango", "nature",
                      "apple", "ball", "cat", "dog", "lime", "ruby",
                      "shine", "tinkter", "ultra", "volly", "wow",
                      "xerox", "yak", "zenon", "joke" };
    int n = sizeof(keys) / sizeof(keys[0]);
  
    // Create the Trie
    struct TrieNode* root = getNode();
    for (int i = 0; i < n; i++)
        insert(root, keys[i]);
  
    // If trie contains words starting
    // from every alphabet
    if (containsAll(root))
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}
输出:
Yes