Given a
Here follow means a full match, such that there is a bijection between a letter in
Output: true
Explanation: here 'a' can be mapped to 'dog' and 'b' can be mapped to 'cat' and vice versa.
Output: false
Explanation: 'a' has two different mappins, so it is not following the pattern.
Output: false
Explanation: here both 'a' and 'b' mapped to same words, so it is not following the pattern.
Contents
Solution 1 - store mapping of each letter to word and word to letter in HashMaps
In this approach, we are going to store mapping of letters of
Implementation details
-
We will create two different
HashMaps to store mappings of letters to words and words to letters. -
As a first step we will spli the input string
s with regular expression' ' (space separated) that returns words in the string as an array.String[] words = s.split(" "); -
In the next step, we will check whether number of characters in
pattern string are equal to number of wordss , if they are not equal then we will returnfalse as strings is not following thepattern string. -
Now for each letter at index
i inpattern string, store corresponding mapped index fromwords array into oneHashMap , and also store mapping from word to the character, the reason why we do this is because to check if different letters inpattern string are pointing to same word or not, if it is then we can returnfalse . -
If mappings from letters from
pattern string towords and vice versa, then we can returntrue .
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(m* n) since we are storing all words from string
Above implementations source code can be found at