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.
My original solution, using 2 HashMaps to store the relationship btw string s and pattern p:
class Solution {
public boolean wordPattern(String pattern, String str) {
String[] s = str.split(" ");
char[] c = pattern.toCharArray();
if(s.length!=c.length) return false;
Map<Character, String> map = new HashMap<>();
Map<String, Character> pam = new HashMap<>();
for(int i=0;i<s.length;i++){
if(map.containsKey(c[i])){
if(!map.get(c[i]).equals(s[i])) return false;
}else{
if(pam.containsKey(s[i])){
if(pam.get(s[i])!=c[i]) return false;
}else {
pam.put(s[i],c[i]);
map.put(c[i],s[i]);
}
}
}
return true;
}
}
But in fact to store the relatioship, we can store the index of strings, and use the previous index to find the realted character, which only needs 1 HashMap.
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (Integer i=0; i<words.length; ++i)
if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
return false;
return true;
}
Note:
You cannot simply compare 2 Integer objects, for “The JVM is caching Integer values. == only works for numbers between -128 and 127”, if the value exceed the boundary, the comparation will always return false.