-
Notifications
You must be signed in to change notification settings - Fork 0
290. Word Pattern
Jacky Zhang edited this page Aug 17, 2016
·
2 revisions
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.
String类题目。
可采用hash map来解。 这里需注意的是不用的pattern的值也不应相同,这一点需要处理:在放入新的k-v pair时,需要判断是否已含有这个value。
public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] attr = str.split(" ");
if(pattern.length() != attr.length) return false;
Map<Character, String> map = new HashMap<Character, String>();
for(int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
if(map.containsKey(c)) {
if(!map.get(c).equals(attr[i])) {
return false;
}
} else {
if(map.containsValue(attr[i])) {
return false;
}
map.put(c, attr[i]);
}
}
return true;
}
}