Given a string, find out if string follows a given pattern or not without using any regular expressions.
Input: string - GraphTreesGraph pattern - aba Output: a->Graph b->Trees Input: string - GraphGraphGraph pattern - aaa Output: a->Graph Input: string - GeeksforGeeks pattern - GfG Output: G->Geeks f->for Input: string - GeeksforGeeks pattern - GG Output: No solution exists
We can solve this problem with the help of Backtracking. For each character in the pattern, if the character is not seen before, we consider all possible sub-strings and recurse to see if it leads to the solution or not. We maintain a map that stores sub-string mapped to a pattern character. If pattern character is seen before, we use the same sub-string present in the map. If we found a solution, for each distinct character in the pattern, we print string mapped to it using our map.
Below is C++ implementation of above idea –
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.
- Write a program to print all permutations of a given string
- Print all palindromic partitions of a string
- Print all permutation of a string using ArrayList
- Check if a given string is sum-string
- Minimize number of unique characters in string
- Print all the combinations of a string in lexicographical order
- Program to generate all possible valid IP addresses from given string | Set 2
- Print all permutations of a string in Java
- Java Program to print distinct permutations of a string
- Generate all permutations of a string that follow given constraints
- Print all the permutations of a string without repetition using Collections in Java
- Print all possible combinations of words from Dictionary using Trie
- Length of longest Palindromic Subsequence of even length with no two adjacent characters same
- Sum of subsets of all the subsets of an array | O(2^N)