2019-02-09
2019-02-09 本文已影响0人
ruicore
LeetCode 290. Word Pattern.jpg
LeetCode 290. Word Pattern
Description
Given a pattern and a string str, find if str 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 str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
描述
给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。
这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。
示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish"
输出: false
示例 3:
输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false
示例 4:
输入: pattern = "abba", str = "dog dog dog dog"
输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
思路
- 模式串中的每个字母要和给定的单词建立一一对应的关系.
- 我们用一个字典建立这种关系;1. 如果当前模式串中的字母不在字典中,我们建立字母和单词的对应关系;2. 如果当前模式串中的字母在字典中:如果当前的单词出现在字典的值中,说明当前单词已经和别的字母建立了对应关系,返回Fasle;如果当前单词没有在字典的值中,我们建立模式串字母和单词的对应关系;3.如果当前模式串字母在字典中,如果字典中模式串对应的值与当前单词不等,我们返回False;4. 如果上面的条件头能够通过,我们最后返回True.
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-02-08 11:19:39
# @Last Modified by: 何睿
# @Last Modified time: 2019-02-09 09:43:27
class Solution:
def wordPattern(self, pattern: 'str', str: 'str') -> 'bool':
# 字典,记录对应关系
match = {}
# 将给定的单词用空格区分
word = str.split(" ")
# 如果长度不相等,直接返回False
if len(pattern) != len(word): return False
for i in range(len(pattern)):
# 如果模式串pattern[i]不在字典中(键)
if pattern[i] not in match:
# 如果此时的单词在字典的值中,说明已经有模式串的字符与当前单词匹配,返回False
if word[i] in match.values():
return False
# 如果单词没有出现在字典的值中,添加当前模式串与单词的对应关系
match[pattern[i]] = word[i]
else:
# 如果当前模式串的键已经在字典中,检查字典的值和当前单词是否相等,不等返回False
if match[pattern[i]] != word[i]:
return False
return True