737. Sentence Similarity II (use hashmap version)
```java
class Solution {
public boolean areSentencesSimilarTwo(String[] sentence1, String[] sentence2, List<List<String>> similarPairs) {
if (sentence1.length != sentence2.length) {
return false;
}
UnionFind uf = new UnionFind(sentence1, sentence2);
for (List<String> pair : similarPairs) {
uf.union(pair.get(0), pair.get(1));
}
for (int i = 0; i < sentence1.length; i++) {
String rootX = uf.find(sentence1[i]);
String rootY = uf.find(sentence2[i]);
if (!rootX.equals(rootY)) {
return false;
}
}
return true;
}
class UnionFind {
private Map<String, String> parent;
UnionFind(String[] sentence1, String[] sentence2) {
this.parent = new HashMap<>();
init(sentence1);
init(sentence2);
}
public void init(String[] sentence) {
for (int i = 0; i < sentence.length; i++) {
if (parent.containsKey(sentence[i])) {
return;
}
parent.put(sentence[i], sentence[i]);
}
}
public String find(String x) {
if (parent.containsKey(x) && parent.get(x) != x) {
parent.put(x, find(parent.get(x)));
}
return parent.get(x) == null ? x : parent.get(x);
}
public void union(String x, String y) {
String rootX = find(x);
String rootY = find(y);
if (rootX != rootY) {
parent.put(rootX, rootY);
}
}
}
}
/*
use union find
1. union first
2. then use find to check similarity
[["great","good"],["fine","good"],["drama","acting"],["skills","talent"]]
"great","good","fine"
drama","acting"
"skills","talent"
*/
```ja
Last updated