## 题目描述：

Given a `pattern` and a string `str`, find if `str` follows the same pattern.

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:

Both pattern and str contains only lowercase alphabetical letters.
Both pattern and str do not have leading or trailing spaces.
Each word in str is separated by a single space.
Each letter in pattern must map to a word with length that is at least 1.

## 题目大意：

pattern和str都只包含小写字母。
pattern和str不包含前导或者后缀空格。
str中的每一个单词之间都由一个空格分开。
pattern中的每一个字母都对应一个长度至少为1的单词。

## Python代码：

``````class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
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
``````

Python代码(1)：

``````def wordPattern(self, pattern, str):
s = pattern
t = str.split()
return map(s.find, s) == map(t.index, t)
``````

Python代码(2)：

``````def wordPattern(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)
``````

Java代码：

``````public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (int i=0; i<words.length; ++i)
if (!Objects.equals(index.put(pattern.charAt(i), i),
index.put(words[i], i)))
return false;
return true;
}
``````

Pingbacks已关闭。

1. JamesFJX 发布于 2016年5月29日 13:50 #

Python代码(2)已经无法通过了，因为多了‘aaa’和‘aa aa aa aa’的case，要考察两者长度是否一样，所以要把return改成

return len(s)==len(t) and len(set(zip(s,t)))==len(set(s))==len(set(t))

才能通过

2. 在线疯狂 发布于 2016年5月31日 15:07 #

感谢提醒！已经对代码做了更正！ :)