290. 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.

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        arr = str.split(" ")
        if len(arr) != len(pattern):
            return False
        f1 = {}
        i = 0
        for x in pattern:
            if x in f1.keys():
                f1[x].append(i)
            else:
                f1[x] = [i];
            i+=1
        
        f2 = {}
        i = 0
        for x in arr:
            if x in f2.keys():
                f2[x].append(i)
            else:
                f2[x] = [i]
            i+=1
        for x in f1.values():
            if x not in f2.values():
                return False
        return True

推荐阅读更多精彩内容

  • 问题: Given a pattern and a string str, find if str follows...
    Cloudox_阅读 116评论 0 0
  • Given a pattern and a string str, find if str follows the...
    Jeanz阅读 30评论 0 0
  • 问题 Given a pattern and a string str, find if str follows ...
    RobotBerry阅读 34评论 0 0
  • Given a patternand a string str, find if strfollows the s...
    exialym阅读 28评论 0 0
  • 心儿为何如此孤独你离去的背影遮住了我观望前方的路途你的依稀笑靥使生活还有几分绚烂人说活着是一种苦我们又怎能如此知足...
    书生初凉阅读 37评论 0 0