Check if the given string of words can be formed from words present in the dictionary | C ++ program to check if a sentence can be formed from a given set of words . ; Function to check if the word is in the dictionary or not ; map to store all words in dictionary with their count ; adding all words in map ; search in map for all words in the sentence ; all words of sentence are present ; Driver Code ; Calling function to check if words are present in the dictionary or not
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool match_words ( string dictionary [ ] , string sentence [ ] , int n , int m ) { unordered_map < string , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ dictionary [ i ] ] ++ ; } for ( int i = 0 ; i < m ; i ++ ) { if ( mp [ sentence [ i ] ] ) mp [ sentence [ i ] ] -= 1 ; else return false ; } return true ; } int main ( ) { string dictionary [ ] = { " find " , " a " , " geeks " , " all " , " for " , " on " , " geeks " , " answers " , " inter " } ; int n = sizeof ( dictionary ) / sizeof ( dictionary [ 0 ] ) ; string sentence [ ] = { " find " , " all " , " answers " , " on " , " geeks " , " for " , " geeks " } ; int m = sizeof ( sentence ) / sizeof ( sentence [ 0 ] ) ; if ( match_words ( dictionary , sentence , n , m ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }