LeetCode----Word Pattern
2015-11-01 20:01
513 查看
Word Pattern
Given a
find if
Here follow means a full match, such that there is a bijection between a letter in
a non-empty word in
Examples:
pattern =
pattern =
pattern =
pattern =
Notes:
You may assume
lowercase letters separated by a single space.
分析:
按模式匹配给定字符串。
我的做法是,先讲模式如“aabb”,构造成模式字典pd={'a':None, 'b':None}。再将给定串如“dog dog cat cat”按空格切分。然后,按顺序去对应串和字典中键,如果不匹配则不符合该模式。最后,再判断字典中不同键值对应的串是否相同,如果相同,也不符合该模式。
代码:
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
pd = dict(map(lambda a: (a, None), list(pattern)))
slst = str.split()
if len(pattern) != len(slst):
return False
for i in range(len(slst)):
if pd[pattern[i]] is None:
pd[pattern[i]] = slst[i]
else:
if pd[pattern[i]] != slst[i]:
return False
s = set()
for i in pd:
s.add(pd[i])
if len(s) != len(pd):
return False
return True
Given a
patternand a string
str,
find if
strfollows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in
patternand
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
patterncontains only lowercase letters, and
strcontains
lowercase letters separated by a single space.
分析:
按模式匹配给定字符串。
我的做法是,先讲模式如“aabb”,构造成模式字典pd={'a':None, 'b':None}。再将给定串如“dog dog cat cat”按空格切分。然后,按顺序去对应串和字典中键,如果不匹配则不符合该模式。最后,再判断字典中不同键值对应的串是否相同,如果相同,也不符合该模式。
代码:
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
pd = dict(map(lambda a: (a, None), list(pattern)))
slst = str.split()
if len(pattern) != len(slst):
return False
for i in range(len(slst)):
if pd[pattern[i]] is None:
pd[pattern[i]] = slst[i]
else:
if pd[pattern[i]] != slst[i]:
return False
s = set()
for i in pd:
s.add(pd[i])
if len(s) != len(pd):
return False
return True
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法