使用 C++ 中两个词典单词的连接形成单词


在此问题中,提供了一个词典和一个单词。我们的任务是检查是否可以使用两个词典单词的连接来形成给定的单词。

在形成给定的单词时,单词的重复是不合法的。

我们举个例子来理解这个问题,

输入

dictionary = {“hello”, “tutorials”, “program” , “problem”, “coding”, “point”} word = “tutorialspoint”

输出

yes

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

说明

tutorialspoint is created using tutorials and point.

要解决此问题,我们将在前缀树(通常称为字典树)中存储词典的所有元素。然后在字典树中搜索单词的前缀,如果找到,将其分成两部分并搜索单词的另一部分。如果找到,则返回 true,否则返回 false。

显示解决方案实现的程序,

示例

 在线演示

#include<bits/stdc++.h>
using namespace std;
#define char_int(c) ((int)c - (int)'a')
#define SIZE (26)
struct TrieNode{
   TrieNode *children[26];
   bool isLeaf;
};
TrieNode *getNode(){
   TrieNode * newNode = new TrieNode;
   newNode->isLeaf = false;
   for (int i =0 ; i< 26 ; i++)
   newNode->children[i] = NULL;
   return newNode;
}
void insert(TrieNode *root, string Key){
   int n = Key.length();
   TrieNode * pCrawl = root;
   for (int i=0; i<n; i++){
      int index = char_int(Key[i]);
      if (pCrawl->children[index] == NULL)
         pCrawl->children[index] = getNode();
      pCrawl = pCrawl->children[index];
   }
   pCrawl->isLeaf = true;
}
int prefixSearch(struct TrieNode *root, string key){
   int pos = -1, level;
   struct TrieNode *pCrawl = root;
   for (level = 0; level < key.length(); level++){
      int index = char_int(key[level]);
      if (pCrawl->isLeaf == true)
         pos = level;
      if (!pCrawl->children[index])
         return pos;
      pCrawl = pCrawl->children[index];
   }
   if (pCrawl != NULL && pCrawl->isLeaf)
   return level;
}
bool isWordCreated(struct TrieNode* root, string word){
   int len = prefixSearch(root, word);
   if (len == -1)
      return false;
   string split_word(word, len, word.length()-(len));
   int split_len = prefixSearch(root, split_word);
   return (len + split_len == word.length());
}
int main() {
   vector<string> dictionary = {"tutorials", "program", "solving", "point"};
   string word = "tutorialspoint";
   TrieNode *root = getNode();
   for (int i=0; i<dictionary.size(); i++)
      insert(root, dictionary[i]);
   cout<<"Word formation using dictionary is ";
   isWordCreated(root, word)?cout<<"possible" : cout<<"not possible";
   return 0;
}

输出

Word formation using dictionary is possible

更新时间: 2020 年 7 月 17 日

158 次浏览

开启你的 职业 生涯

完成课程并获得认证

开始
广告