python算法--leetcode练习题(标记比对)

这是一个leetcode上面的算法题,记录这里,算是记录了

下面是题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.

他说的是什么

这个是一个简单的字符和list匹配问题,期望字符串的分布与list分布相同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#encoding: utf-8
'''
Created Time: 一 8/ 1 18:31:07 2016
mail: liangyou.qiao@shuyun.com
Author: liangyou.qiao
File Name: wordPattern.py'
'''
def wordPattern(pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
pattern_list = list(pattern)
str_list = str.split()
def label(lis):
"""
:type lis: list
rtype: insert_lis:list
"""
dic = {}
insert_lis = []
n = 0
for i in lis:
if i not in dic:
dic[i] = n
n +=1
insert_lis.append(dic[i])
else:
insert_lis.append(dic[i])
return insert_lis
return label(pattern_list) == label(str_list)
if __name__ == "__main__":
a = "aaba"
b = "dog cat cat fish"
wordPattern(a,b)