290. Word Pattern
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.
Solution 1.
Keep two hash tables, one map from pattern.charAt[i] to str[i], one map from the other direction. if not exists in either map, update the key-value pair. then compare whether both maps match each other.
public class Solution {
public boolean wordPattern(String pattern, String str) {
Map<Character, String> m1 = new HashMap<>();
Map<String, Character> m2 = new HashMap<>();
String[] word = str.split(" ");
if(pattern.length() != word.length) return false;
for(int i=0;i<pattern.length(); i++){
char ch = pattern.charAt(i);
if(!m1.containsKey(ch)) m1.put(ch, word[i]);
if(!m2.containsKey(word[i])) m2.put(word[i], ch);
if(!Objects.equals(ch, m2.get(word[i])) || !Objects.equals(word[i], m1.get(ch))){
return false;
}
}
return true;
}
}
Solution 2.
There is one more smart solution that take advantage of Map.put()'s return value. and more importantly it utilizes a un-generic map from old java which is not safe.
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (int i=0; i<words.length; ++i)
if (!Objects.equals(index.put(pattern.charAt(i), i),
index.put(words[i], i)))
return false;
return true;
}
a bit safer improvement
public class Solution {
public boolean wordPattern(String pattern, String str) {
Map<Character, Integer> m1 = new HashMap<>();
Map<String, Integer> m2 = new HashMap<>();
String[] words = str.split(" ");
if(words.length != pattern.length()) return false;
for(int i=0; i<pattern.length(); i++){
if(!Objects.equals(m1.put(pattern.charAt(i), i),
m2.put(words[i], i))) return false;
}
return true;
}
}