p290

LeetCode p290 Word Pattern 题解

1.题目:

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.

题意:

判断字符串格式是否与图章一致。

2.解题思路:

使用hashmap和hashset

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] list = str.split(" ");
if (pattern.length() != list.length)
return false;
HashMap<Character, String> hashMap = new HashMap<Character, String>();
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < pattern.length(); i++) {
String aString = hashMap.get(pattern.charAt(i));
if (aString == null) {
if (set.contains(list[i]))
return false;
hashMap.put(pattern.charAt(i), list[i]);
set.add(list[i]);
} else {
if (!list[i].equals(aString))
return false;
}
}
return true;
}
}

4.一些总结: