September LeetCoding Challenge, Day 7: Word Pattern
September 8, 2020The problem for September 7 is Word Pattern. You’re given two
strings. One of them consists of lowercase letters and the other consists of
lowercase letters separated by spaces. You want to find out if a
bijection exists between the characters of the first string and the
words in the second string. In other words, you want to return true
if there
is a one-to-one correspondence between the characters of the first string and
the characters of the second string, and false
otherwise.
If the number of words is different from the number of characters, then you can be sure that no bijection exists. If the number of words is the same, we can go word by word and check if a word happens to be mapped to different characters. If it does, then no bijection exists. This is still not sufficient to determine a bijection, since the same character can still be mapped to different words. In order for a bijection to exist, the number of different words must be equal to the number of different characters. Combining all those checks lets us determine if there is a one-to-one correspondence between characters and words. The following is an implementation of the previous idea: