LeetCode 290. Word Pattern

题目

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.

Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

分析

单词模式,这一题和同构字符串类似

  • 输入:单词模式和字符串形式的字符串数组
  • 条件:无
  • 任务:判断单词模式和字符串形式的字符串数组的模式是否相同
  • 输出:True or False

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def wordPattern(self, pattern, str):
s = pattern
t = str.split()
return map(s.find, s) == map(t.index, t)
def wordPattern1(self, pattern, str):
f = lambda s: map({}.setdefault, s, range(len(s)))
return f(pattern) == f(str.split())
def wordPattern2(self, pattern, str):
s = pattern
t = str.split()
return len(set(zip(s, t))) == len(set(s)) == len(set(t)) and len(s) == len(t)

点评

这一题和同构字符串类似,用字符串的 map 函数可以编码字符串,而数组的编码函数用的是 index