Leetcode 290. Word Pattern & 291. Word Pattern II (python)

word pattern

题目

在这里插入图片描述

解法:双hashmap

判断他们是否matching的关键在于,pattern中的某个字母和s中的单词是不是双向1-1对应的。要表达这种双向1-1对应的关系可以用两个字典,每个字典表示一种映射方向

class Solution:
    def wordPattern(self, pattern: str, str: str) -> bool:
        map_from_letter_to_word = {
   }
        map_from_word_to_letter = {
   }
        
        st = str.split(' ')
        if len(st) != len(pattern):
            return False
        
        for x,y in zip(pattern,st):
            if x not in map_from_letter_to_word:
                map_from_letter_to_word[x] = y
            if y not in map_from_word_to_letter:
                map_from_word_to_letter[y] = x
            if map_from_word_to_letter[y] != x or map_from_letter_to_word[x] != y:
                return False
        return True

word pattern II

题目:

在这里插入图片描述

解法:双hashmap+backtracking

这道题跟上面一道题的唯一区别在于,现在的S是连续的。对于连续的S,比较常见的做法就是用backtracking进行暴力搜索。通过backtracking将他分割成所有可能的combination,并且判断双向的对应关系是否符合。具体流程如下:

  • 给定一个pattern所在的位置i,s中所在的位置j
  • 首先判断pattern[i]有没有已经存在的映射,如果有的话,那么现在s[j:j+k]对应的word要和现在pattern[i]对应的word相同,然后进行下一层matching,否则证明已经不符合matching
  • 如果pattern[i]不存在已知映射,那么我们应该枚举pattern[i]映射到以j为index开始的任意的s中的sub string对应,这边就需要backtracking

看文字解释确实有点费解,看代码可能会更好理解

class Solution:
    def wordPatternMatch(self, pattern: str
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值