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
相关推荐
十八岁讨厌编程1 小时前
【算法训练营Day26】动态规划part2
算法·动态规划
智者知已应修善业2 小时前
【C++无数组矩阵对角线平均值保留2位小数】2022-11-18
c语言·c++·经验分享·笔记·算法·矩阵
papership3 小时前
【入门级-算法-6、排序算法: 计数排序】
数据结构·算法·排序算法
pengpeng023 小时前
力扣每日一题 611. 有效三角形的个数
算法·leetcode·职场和发展
2401_840105203 小时前
GESP C++5级 2025年6月编程2题解:最大公因数
数据结构·c++·算法
未知陨落3 小时前
LeetCode:56.子集
算法·leetcode·深度优先
PAK向日葵3 小时前
【算法导论】一道涉及到溢出处理的笔试题
算法·面试
哈泽尔都4 小时前
运动控制教学——5分钟学会样条曲线算法!(三次样条曲线,B样条曲线)
c++·人工智能·算法·机器学习·matlab·贪心算法·机器人
小镇学者4 小时前
【NOI】在信奥赛中 什么是函数交互题?
算法
未知陨落4 小时前
LeetCode:62.N皇后
算法·leetcode