public class Solution {
public boolean wordPattern(String pattern, String str) {
Map<Character, String> map1 = new HashMap<>();
Map<String, Character> map2 = new HashMap<>();
String[] strs = str.trim().split("\\s+");
char[] patterns = pattern.toCharArray();
if(patterns.length != strs.length){
return false;
}
for(int i = 0; i < patterns.length; i++){
if(!map1.containsKey(patterns[i])){
map1.put(patterns[i], strs[i]);
}else{
if(!map1.get(patterns[i]).equals(strs[i])){
return false;
}
}
}
for(int i = 0; i < strs.length; i++){
if(!map2.containsKey(strs[i])){
map2.put(strs[i], patterns[i]);
}else{
if(map2.get(strs[i]) != patterns[i]){
return false;
}
}
}
return true;
}
}
[LeetCode] 290. Word Pattern
最新推荐文章于 2017-03-31 11:39:00 发布