【英文题目】(学习英语的同时,更能理解题意哟~)
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
【中文题目】
给定一种 pattern(模式)
和一个字符串 str
,判断 str
是否遵循相同的模式。
这里的遵循指完全匹配,例如, pattern
里的每个字母和字符串 str
中的每个非空单词之间存在着双向连接的对应模式。
示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish"
输出: false
【思路】
比较pattern的每个字符以及str的每个单词是否一一对应即可。
【代码】
python版本
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
strls = str.split()
if len(strls) != len(pattern):
return False
d = {}
dr = {}
for i, p in enumerate(pattern):
# 要求d[p] == strls[i] and dr[strls[i]] == p
if p not in d:
d[p] = strls[i]
elif d[p] != strls[i]:
return False
if strls[i] not in dr:
dr[strls[i]] = p
elif dr[strls[i]] != p:
return False
return True