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
相关推荐
先做个垃圾出来………21 分钟前
汉明距离(Hamming Distance)
开发语言·python·算法
小羊在奋斗1 小时前
【LeetCode 热题 100】二叉树的最大深度 / 翻转二叉树 / 二叉树的直径 / 验证二叉搜索树
算法·leetcode·职场和发展
2301_794461572 小时前
力扣-283-移动零
算法·leetcode·职场和发展
编程绿豆侠2 小时前
力扣HOT100之二叉树:98. 验证二叉搜索树
算法·leetcode·职场和发展
技术流浪者2 小时前
C/C++实践(十)C语言冒泡排序深度解析:发展历史、技术方法与应用场景
c语言·数据结构·c++·算法·排序算法
I AM_SUN3 小时前
98. 验证二叉搜索树
数据结构·c++·算法·leetcode
学习中的码虫3 小时前
数据结构基础排序算法
数据结构·算法·排序算法
yidaqiqi4 小时前
[目标检测] YOLO系列算法讲解
算法·yolo·目标检测
飞天狗1114 小时前
2024 山东省ccpc省赛
c++·算法
卡尔曼的BD SLAMer4 小时前
计算机视觉与深度学习 | Python实现EMD-SSA-VMD-LSTM-Attention时间序列预测(完整源码和数据)
python·深度学习·算法·cnn·lstm