737.Sentence Similarity II
class Solution {
public boolean areSentencesSimilarTwo(String[] words1, String[] words2, String[][] pairs) {
if(words1.length != words2.length)
return false;
Map<String, String> roots = new HashMap<>();
for(String[] pair : pairs){
roots.put(pair[0], pair[0]);
roots.put(pair[1], pair[1]);
}
for(String[] pair : pairs){
String root1 = find(roots, pair[0]);
String root2 = find(roots, pair[1]);
if(!root1.equals(root2)){
roots.put(root1, root2);
}
}
for(int i = 0; i < words1.length; i++){
if(words1[i].equals(words2[i]))
continue;
String root1 = find(roots, words1[i]);
String root2 = find(roots, words2[i]);
if(root1 == null || root2 == null)
return false;
if(!root1.equals(root2))
return false;
}
return true;
}
public String find(Map<String, String> roots, String word){
if(!roots.containsKey(word)){
return null;
}
else if(roots.get(word).equals(word)){
return word;
}
else
return find(roots, roots.get(word));
}
}