LeetCode ---- Word Pattern
Word Pattern
GivenpatternAnd a stringstr, Find ifstrFollows the same pattern.
Here follow means a full match, such that there is a bijection between a letter inpatternAnd a non-empty word instr.
Examples:
- Pattern =
abba, Str =dog cat cat dogShocould return true.
- Pattern =
abba, Str =dog cat cat fishShocould return false.
- Pattern =
aaaa, Str =dog cat cat dogShocould return false.
- Pattern =
abba, Str =dog dog dog dogShocould return false.
Notes:
You may assumepatternContains only lowercase letters, andstrContains lowercase letters separated by a single space.
Analysis:
Matches the specified string by mode.
My approach is to build a Pattern Dictionary pd = {'A': None, 'B': None} based on a pattern such as "aabb }. Split the given string, such as "dog cat", by space. Then, the corresponding string and the dictionary key are sorted in order. If they do not match, the mode is not met. Finally, determine whether the strings corresponding to different key values in the dictionary are the same. If the strings are the same, they do not match the pattern.
Code:
class Solution(object): def wordPattern(self, pattern, str): :type pattern: str :type str: str :rtype: bool pd = dict(map(lambda a: (a, None), list(pattern))) slst = str.split() if len(pattern) != len(slst): return False for i in range(len(slst)): if pd[pattern[i]] is None: pd[pattern[i]] = slst[i] else: if pd[pattern[i]] != slst[i]: return False s = set() for i in pd: s.add(pd[i]) if len(s) != len(pd): return False return True