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
相关推荐
纪念 2298 分钟前
C++ 算法(模拟)
开发语言·c++·算法
揽星河..11 分钟前
【C语言】函数
c语言·算法
zwc321043205514 分钟前
Day 2:图像内存、数据类型与stride
c++·人工智能·opencv·算法·计算机视觉
重生之小比特28 分钟前
【算法拾光】模拟|提莫攻击 + N 字形变换
算法·模拟
東隅已逝,桑榆非晚1 小时前
AVL数实现
c++·笔记·学习·算法
驭渊的小故事1 小时前
LeetCode 算法题解:滑动窗口与数组合并的实战应用
算法·leetcode·职场和发展
.YM.Z1 小时前
优选算法——【双指针算法2】C++实现
开发语言·c++·算法
文丑颜不良啊1 小时前
LeetCode1501~1520题目解析
java·leetcode
zwc32104320552 小时前
第四周第五天——重构成类
c++·人工智能·opencv·算法·计算机视觉
Navigator_Z3 小时前
LeetCode //C - 1311. Get Watched Videos by Your Friends
c语言·算法·leetcode