Given a dictionary of words, find all strings that matches the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary.
Input: dict = ["abb", "abc", "xyz", "xyy"]; pattern = "foo" Output: [xyy abb] Explanation: xyy and abb have same character at index 1 and 2 like the pattern Input: dict = ["abb", "abc", "xyz", "xyy"]; pat = "mno" Output: [abc xyz] Explanation: abc and xyz have all distinct characters, similar to the pattern Input: dict = ["abb", "abc", "xyz", "xyy"]; pattern = "aba" Output:  Explanation: Pattern has same character at index 0 and 2. No word in dictionary follows the pattern. Input: dict = ["abab", "aba", "xyz", "xyx"]; pattern = "aba" Output: [aba xyx] Explanation: aba and xyx have same character at index 0 and 2 like the pattern
The idea is to encode the pattern in such a way that any word from the dictionary that matches the pattern will have same hash as that of the pattern after encoding. We iterate through all words in dictionary one by one and print the words that have same hash as that of the pattern.
Below is the implementation of above idea –
The idea is to traverse both the pattern and word in parallel and for every first occurrence of any character in pattern we map it to the corresponding character present in word, and for any subsequent occurrence of the same character in pattern, there must me the same character in word which was earlier mapped.
For first occurrence of any character in pattern, we do ch[pattern[i]] = word[i].
and subsequent occurrence of any character must satisfy ch[pattern[i]] == word[i].
Below is the implementation of the above approach:
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Case-specific Sorting of Strings
- Program to find all match of a regex in a string
- Count strings that end with the given pattern
- Generate all binary strings from given pattern
- Python Dictionary to find mirror characters in a string
- Dictionary and counter in Python to find winner of election
- Given a sorted dictionary of an alien language, find order of characters
- Find largest word in dictionary by deleting some characters of given string
- Find all palindromic sub-strings of a given string | Set 2
- Find uncommon characters of the two strings | Set 2
- Find uncommon characters of the two strings
- Given two numbers as strings, find if one is a power of other
- Given two strings, find if first string is a subsequence of second
- Find if a string is interleaved of two other strings | DP-33
- Find all distinct palindromic sub-strings of a given string