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
相关推荐
DDAshley12611 小时前
【PaddleOCR】从零开始训练自己的模型--详细教程
算法·计算机视觉
梁辰兴11 小时前
数据结构:查找
数据结构·算法·查找·顺序查找·折半查找·分块查找
Brookty11 小时前
【算法】双指针(一)移动零
学习·算法
THMAIL12 小时前
机器学习从入门到精通 - 循环神经网络(RNN)与LSTM:时序数据预测圣经
人工智能·python·rnn·算法·机器学习·逻辑回归·lstm
程序员Xu12 小时前
【LeetCode热题100道笔记】二叉树的直径
笔记·算法·leetcode
superlls12 小时前
(数据结构)哈希碰撞:线性探测法 vs 拉链法
算法·哈希算法·散列表
ShineWinsu12 小时前
对于单链表相关经典算法题:206. 反转链表及876. 链表的中间结点的解析
java·c语言·数据结构·学习·算法·链表·力扣
再睡一夏就好12 小时前
【C++闯关笔记】STL:list 的学习和使用
c语言·数据结构·c++·笔记·算法·学习笔记
Ka1Yan13 小时前
MySQL索引优化
开发语言·数据结构·数据库·mysql·算法