Given a pattern
and a string str
, find if str
follows the same pattern.
Here follow means a full match, such that there was a bijection between a letter in and pattern
a non-empty word in str
.
Examples:
- pattern =
"abba"
, str = "dog cat cat dog"
should return true.
- pattern =
"abba"
, str = "dog cat cat fish"
should return FALSE.
- pattern =
"aaaa"
, str = "dog cat cat dog"
should return FALSE.
- pattern =
"abba"
, str = "dog dog dog dog"
should return FALSE.
Notes:
Assume contains only pattern
lowercase letters, and contains lowercase letters separated by str
a single space.
First check that the length is consistent
Then determine if each map relationship is unique
classsolution (object):defWordpattern (self, Pattern, str): STR= Str.split (' ') ifLen (pattern)! =len (str):returnFalse H= {} forIinchRange (len (str)):if notH.has_key (Pattern[i]):ifStr[i] not inchh.values (): H[pattern[i]]=Str[i]Else: returnFalseElse: ifH[pattern[i]]! =Str[i]:returnFalsereturnTrue
Leetcode 290 Word Pattern