Word Pattern

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and 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.

使用字典dict分别记录pattern到word的映射以及word到pattern的映射

这道题和题目Isomorphic Strings十分类似

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        hashmapP = {}
        hashmapS = {}
        str = str.split()
        if len(str) != len(pattern):
            return False
        for i in range(len(pattern)):
            if hashmapP.get(pattern[i]):
                if hashmapP[pattern[i]] != str[i]:
                    return False
            else:
                hashmapP[pattern[i]] = str[i]

        for j in range(len(str)):
            if hashmapS.get(str[j]):
                if hashmapS[str[j]] != pattern[j]:
                    return False
            else:
                hashmapS[str[j]] = pattern[j]

        return True

Last updated

Was this helpful?