给定一种规律 pattern
和一个字符串 str
,判断 str
是否遵循相同的规律。
input: pattern = "abba", str = "dog cat cat dog" output: true
class Solution {
public boolean wordPattern(String pattern, String s) {
Map<Character,String> map = new HashMap<Character,String>();
String[] strs = s.split(" ");
int len = strs.length;
if(pattern.length() != len){
return false;
}
for (int i = 0; i < len; i++) {
char ch = pattern.charAt(i);
if(!map.containsKey(ch) && !map.containsValue(strs[i])){
map.put(ch,strs[i]);
} else if(map.containsKey(ch) && map.containsValue(strs[i])){
if(!map.get(ch).equals(strs[i])){
return false;
}
} else {
return false;
}
}
return true;
}
}