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
相关推荐
INGNIGHT2 小时前
270 · 电话号码的字母组合II(Trie)
linux·算法
2401_839080543 小时前
C++常见八股
数据结构·c++·算法
青山是哪个青山3 小时前
LeetCode 188:买卖股票的最佳时机 IV
算法
mikuyyds3 小时前
geo-toolbox 插件算法解析:RUSLE 与 MUSLE 的工程化落地
算法·rust·gis
Tisfy3 小时前
LeetCode 3498.字符串的反转度:一次遍历
leetcode·字符串·题解·遍历
a187927218313 小时前
【算法】树(二):队列与祖先——BFS 骨架三配件、短路透传与合流
算法·leetcode·二叉树··bfs·算法讲解·树遍历
syagain_zsx4 小时前
算法基础篇 · 03 枚举(C++ 题解)
c++·算法·二进制·枚举
weixin_307779134 小时前
C++代码实现MATLAB中的ode23tb函数功能
开发语言·c++·算法·matlab
我是章汕呐5 小时前
地级市能源消耗量及消耗强度数据【2006-2023年】平衡面板
人工智能·经验分享·算法·回归
charliejohn5 小时前
计算机考研 408 数据结构 堆的插入与删除 堆排序
算法