Word formation using concatenation of two dictionary words in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a dictionary and a word. Our task is to check if the given wors can be formed using the concatenation of two dictionary words.

While forming given words repetition of words is not legal.

Let’s take an example to understand the problem,

Input

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

Output

yes

Explanation

tutorialspoint is created using tutorials and point.

To solve this problem, we will store all elements of the dictionary in a prefix tree commonly known as a trie. And then search for the prefix of the word in the trie, if found split it into two and search other part of the word. If it is found return true else false.

Program to show the implementation of the solution,

Example

 Live Demo

#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;
}

Output

Word formation using dictionary is possible
raja
Published on 17-Jul-2020 14:32:53
Advertisements