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
A:You may assume
pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.就是简单的双映射
public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] A= str.split("\\s+");
Map<Character, String> map1 = new HashMap();
Map<String,Character> map2 = new HashMap();
if(pattern.length() != A.length)
return false;
for(int i =0;i< pattern.length();i++){
char ch = pattern.charAt(i);
String ss = A[i];
if(map1.containsKey(ch) ){
if(! map1.get(ch).equals(ss))
return false;
}
map1.put(ch,ss);
// check reverse
if(map2.containsKey(ss)){
if(! map2.get(ss).equals(ch))
return false;
}
map2.put(ss, ch);
}
return true;
}
}
Errors:
好久没刷题了, check String相等的时候, 直接用了等号
No comments:
Post a Comment