Leetcode 290. Word Pattern

Problem

Given a pattern and a string s, find if s 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 s.

Algorithm

Use the dictionary to save the two list.

Code

python3 复制代码
class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        plen = len(pattern)
        dict_p = dict()
        dict_s = dict()
        word = ""
        index = 0
        for c in s:
            if c >= 'a' and c <= 'z':
                word += c
            else:
                if index >= plen:
                    return False
                pi = pattern[index]
                if index < plen and not pi in dict_p and not word in dict_s:
                    dict_p[pi] = word
                    dict_s[word] = pi
                elif pi in dict_p and dict_p[pi] != word or word in dict_s and dict_s[word] != pi:
                    return False
                index += 1
                word = ""
        
        if index >= plen:
            return False
        pi = pattern[index]
        if index < plen and not pi in dict_p and not word in dict_s:
            dict_p[pi] = word
            dict_s[word] = pi
        elif pi in dict_p and dict_p[pi] != word or word in dict_s and dict_s[word] != pi:
            return False

        for i in range(index, plen):
            if not pattern[i] in dict_p:
                return False
        return True
相关推荐
丁浩6662 小时前
Python机器学习---2.算法:逻辑回归
python·算法·机器学习
伏小白白白2 小时前
【论文精度-2】求解车辆路径问题的神经组合优化算法:综合展望(Yubin Xiao,2025)
人工智能·算法·机器学习
无敌最俊朗@3 小时前
数组-力扣hot56-合并区间
数据结构·算法·leetcode
囚生CY3 小时前
【速写】优化的深度与广度(Adam & Moun)
人工智能·python·算法
码农多耕地呗4 小时前
力扣94.二叉树的中序遍历(递归and迭代法)(java)
数据结构·算法·leetcode
微笑尅乐4 小时前
BFS 与 DFS——力扣102.二叉树的层序遍历
leetcode·深度优先·宽度优先
懒羊羊不懒@4 小时前
Java基础语法—最小单位、及注释
java·c语言·开发语言·数据结构·学习·算法
白云千载尽5 小时前
leetcode 912.排序数组
算法·leetcode·职场和发展
哆啦刘小洋5 小时前
Tips:预封装约束的状态定义
算法
代码充电宝5 小时前
LeetCode 算法题【简单】290. 单词规律
java·算法·leetcode·职场和发展·哈希表