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
相关推荐
Zero-Talent30 分钟前
位运算算法
算法
不穿格子的程序员33 分钟前
从零开始刷算法——双指针-三数之和&接雨水
算法·双指针
无限进步_1 小时前
C语言数组元素删除算法详解:从基础实现到性能优化
c语言·开发语言·windows·git·算法·github·visual studio
松涛和鸣1 小时前
16、C 语言高级指针与结构体
linux·c语言·开发语言·数据结构·git·算法
Booksort1 小时前
【LeetCode】算法技巧专题(持续更新)
算法·leetcode·职场和发展
OJAC1111 小时前
2026高校毕业生1270万!但这些学生却被名企用高薪“提前预定”!
算法
Controller-Inversion2 小时前
岛屿问题(dfs典型问题求解)
java·算法·深度优先
小白程序员成长日记2 小时前
力扣每日一题 2025.11.28
算法·leetcode·职场和发展
Swift社区2 小时前
LeetCode 435 - 无重叠区间
算法·leetcode·职场和发展
sin_hielo2 小时前
leetcode 1018
算法·leetcode