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
相关推荐
共享家95272 小时前
链表操作:分区与回文判断
c语言·开发语言·数据结构·leetcode·链表
ClaNNEd@2 小时前
大话数据结构第二章,算法笔记
数据结构·笔记·算法
圣保罗的大教堂4 小时前
《算法笔记》9.3小节——数据结构专题(2)->树的遍历 问题 A: 树查找
算法
自信的小螺丝钉6 小时前
Leetcode 1277. 统计全为 1 的正方形子矩阵 动态规划
leetcode·矩阵·动态规划
乌云暮年6 小时前
算法刷题整理合集(四)
java·开发语言·算法·dfs·bfs
Luo_LA7 小时前
【排序算法对比】快速排序、归并排序、堆排序
java·算法·排序算法
AI技术控7 小时前
机器学习算法实战——天气数据分析(主页有源码)
算法·机器学习·数据分析
oioihoii7 小时前
C++20 中的同步输出流:`std::basic_osyncstream` 深入解析与应用实践
c++·算法·c++20
猪猪成7 小时前
【图论】FLOYD弗洛伊德算法-最短路径
学习·算法·图论
HR Zhou7 小时前
群体智能优化算法-粒子群优化算法(Particle Swarm Optimization, PSO,含Matlab源代码)
算法·matlab·优化·智能优化算法