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
using System ; using System . Collections . Generic ; class GFG { static Boolean match_words ( String [ ] dictionary , String [ ] sentence , int n , int m ) { Dictionary < String , int > mp = new Dictionary < String , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . ContainsKey ( dictionary [ i ] ) ) { mp [ dictionary [ i ] ] = mp [ dictionary [ i ] ] + 1 ; } else { mp . Add ( dictionary [ i ] , 1 ) ; } } for ( int i = 0 ; i < m ; i ++ ) { if ( mp . ContainsKey ( sentence [ i ] ) && mp [ sentence [ i ] ] > 0 ) mp [ sentence [ i ] ] = mp [ sentence [ i ] ] - 1 ; else return false ; } return true ; } public static void Main ( String [ ] args ) { String [ ] dictionary = { " find " , " a " , " geeks " , " all " , " for " , " on " , " geeks " , " answers " , " inter " } ; int n = dictionary . Length ; String [ ] sentence = { " find " , " all " , " answers " , " on " , " geeks " , " for " , " geeks " , " geeks " } ; int m = sentence . Length ; if ( match_words ( dictionary , sentence , n , m ) ) Console . WriteLine ( " YES " ) ; else Console . WriteLine ( " NO " ) ; } }