Problem Description
A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.You are to find all the hat’s words in a dictionary.
#include<iostream> #include<string.h> using namespace std; #define MAX_SIZE 26 typedef struct trie_node{ bool is_terminated; char data; struct trie_node *child[MAX_SIZE]; }TrieNode, *TrieTree; TrieNode *create_node(char c) { TrieNode *temp = (TrieNode*)malloc(sizeof(TrieNode)); temp->is_terminated = false; temp->data = c; for(int i = 0;i < MAX_SIZE; i++) temp->child[i] = NULL; return temp; } void trie_insert(TrieTree *T, char *s) { TrieNode *p = *T; while(*s) { if(p->child[*s - 'a'] == NULL) { p->child[*s - 'a'] = create_node(*s); } p = p->child[*s - 'a']; s++; } p->is_terminated = true; } bool trie_search(TrieTree T, char *s) { TrieNode *p = T; while(p && *s) { if(p->child[*s - 'a'] == NULL) { return false; } else { p = p->child[*s - 'a']; s++; } } return (*s == '\0') && p->is_terminated; } bool find_hat_word(TrieTree T, char *s) { TrieNode *p = T; while(p && *s) { if(p->is_terminated) { if(trie_search(T, s)) { return true; break; } } p = p->child[*s - 'a']; s++; } return false; } void main() { TrieTree T = create_node(' '); char *s[]= {"a", "ahat", "hat", "hatword", "hziee", "word", "test", "case", "testcase"}; int num = sizeof(s) /sizeof(char*); for(int i =0;i < num; i++) trie_insert(&T, s[i]); for(i = 0; i < num; i++) if(find_hat_word(T, s[i])) cout << s[i] << endl; }