Check if the given string of words can be formed from words present in the dictionary | Java 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
import java . util . * ; class GFG { static boolean match_words ( String dictionary [ ] , String sentence [ ] , int n , int m ) { Map < String , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( dictionary [ i ] ) ) { mp . put ( dictionary [ i ] , mp . get ( dictionary [ i ] ) + 1 ) ; } else { mp . put ( dictionary [ i ] , 1 ) ; } } for ( int i = 0 ; i < m ; i ++ ) { if ( mp . containsKey ( sentence [ i ] ) ) mp . put ( sentence [ i ] , mp . get ( 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 " } ; int m = sentence . length ; if ( match_words ( dictionary , sentence , n , m ) ) System . out . println ( " YES " ) ; else System . out . println ( " NO " ) ; } }