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:
"abba", str = "dog
cat cat dog" should return true."abba", str = "dog
cat cat fish" should return false."aaaa", str = "dog
cat cat dog" should return false."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.
Subscribe to see which companies asked this question
解题分析:
题目的意思是给出一个字符串 str, 再给出一个模式 pattern,然后要求就是判断给出的字符串是否和给出的模式相匹配,
匹配的话就返回True, 否则返回False.
思路一:
利用hash思想将pattern做索引,str为值存储,与str为索引,pattern为值进行匹配。
# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
def wordPattern(self, pattern, str):
words = str.split()
if len(pattern) != len(words):
return False
ptnDict, wordDict = {}, {}
for ptn, word in zip(pattern, words):
if ptn not in ptnDict:
ptnDict[ptn] = word
if word not in wordDict:
wordDict[word] = ptn
if wordDict[word] != ptn or ptnDict[ptn] != word:
return False
return True
思路二:
利用位置进行匹配。
使用 index 以及,map,find 函数。
# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
def wordPattern(self, pattern, str):
s = pattern
t = str.split()
return map(s.find, s) == map(t.index, t)
(LeetCode)Word Pattern --- 模式匹配
原文:http://blog.csdn.net/u012965373/article/details/52217651