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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 問題: Given a pattern and a string str, find if str follows...
    Cloudox_閱讀 469評論 0 0
  • Given a pattern and a string str, find if str follows the...
    Jeanz閱讀 319評論 0 0
  • 問題 Given a pattern and a string str, find if str follows ...
    RobotBerry閱讀 256評論 0 0
  • Given a patternand a string str, find if strfollows the s...
    exialym閱讀 200評論 0 0
  • 心兒為何如此孤獨你離去的背影遮住了我觀望前方的路途你的依稀笑靨使生活還有幾分絢爛人說活著是一種苦我們又怎能如此知足...
    初涼閱讀 489評論 0 0

友情鏈接更多精彩內(nèi)容