《Leetcode of December》290.单词规律

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        word2ch = dict()
        ch2word = dict()
        words = s.split()
        if len(pattern) != len(words):
            return False
        '''
        zip之后的ch和word 形成一种双射关系,如果不满足双射就返回false
        a dog
        b cat
        b cat
        a dog
        '''
        for ch, word in zip(pattern, words):
            if (word in word2ch and word2ch[word] != ch) or (ch in ch2word and ch2word[ch] != word):
                return False
            word2ch[word] = ch
            ch2word[ch] = word
    
        return True

        '''
        ①使用两个hash表记录位置
        ②如果出现的位置都是相同的,那么就说明pattern和str完全匹配
        '''
        s = s.split()
        if len(pattern)!=len(s):
            return False
        
        dic_p=defaultdict(list)
        dic_s=defaultdict(list)
        for i in range(len(pattern)):
            dic_p[pattern[i]].append(i)
            dic_s[s[i]].append(i)
        index1 = [item[1] for item in dic_p.items()]
        index2 = [item[1] for item in dic_s.items()]   
        return  index1==index2
  • 两种方法,法1官方解答,法2自己解答
    • 使用双射的思想仅遍历依次就可可以了
    • 也是双射的思想不过是遍历了两次,然后比较出现的index是否相同

总结:hash表的一个简单应用。 

猜你喜欢

转载自blog.csdn.net/weixin_37724529/article/details/111279875