LeetCode 290. Word Pattern
考点 | 难度 |
---|---|
Hash Table | Easy |
题目
Given a pattern
and a string s
, find if s
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 s
.
思路
用HashMap.put()
的返回值判断。如果key没有重复则返回null
,如果有重复则返回原始map中key对应的value。在这道题中,对于pattern
中一个之前已经出现过的字母,返回的value是这个字母上次出现时在pattern
中的位置。s
中的单词同理。所以只需要比较对应位置的两个返回值是否相同即可。
答案
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (Integer i=0; i<words.length; ++i)
if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
return false;
return true;
}
**解法参考@StefanPochmann