[leetcode: Python]290.Word Pattern
来源:互联网 发布:项目 书籍 商务 知乎 编辑:程序博客网 时间:2024/06/07 07:16
题目:
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.
题意:
如上所述,注意,模式只包含小写字母,分隔符是空格。
方法一:性能58ms
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ s = str.split(' ') if len(pattern) != len(s): return False h = {} mapval = [] for i in range(len(pattern)): if pattern[i] in h: if h[pattern[i]] != s[i]: return False else: if s[i] in mapval: return False h[pattern[i]] = s[i] mapval.append(s[i]) return True
方法二:性能32ms
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ d = {} d1 = {} l = str.split(" ") if len(l) != len(pattern): return False for i in range(len(pattern)): if pattern[i] not in d: d[pattern[i] ] = l[i] if l[i] not in d1: d1[l[i]] = pattern[i] else: return False else: if l[i] != d[pattern[i]]: return False return True
0 0
- [leetcode: Python]290.Word Pattern
- 【leetcode】290. Word Pattern(Python & C++)
- 【leetcode】290. Word Pattern
- 【leetcode】290. Word Pattern
- 290. Word Pattern LeetCode
- Leetcode 290. Word Pattern
- 【LeetCode】290. Word Pattern
- LeetCode-290. Word Pattern
- LeetCode *** 290. Word Pattern
- leetcode 290. Word Pattern
- LeetCode 290. Word Pattern
- LeetCode 290. Word Pattern
- [leetcode] 290. Word Pattern
- 【LeetCode】290. Word Pattern
- LeetCode-290.Word Pattern
- Leetcode 290. Word Pattern
- leetcode:290. Word Pattern
- 290.[Leetcode]Word Pattern
- Note4、const
- redis 三(数据类型)
- SSM项目---淘淘商城(IDEA开发)
- POJ 2387 Til the Cows Come Home 最短路 Dijstra
- Java内存模型
- [leetcode: Python]290.Word Pattern
- linux shell
- 关于tomcat发布项目404的奇葩问题
- BZOJ3173 [Tjoi2013]最长上升子序列
- 玲珑杯-No Game No Life
- 使用IDEA创建maven父子工程
- 什么是回调函数?
- C#获取系统当前日期时间
- 处理Linux中的^M字符