题目地址:
https://leetcode.com/problems/sentence-similarity-ii/
给定一个列表,列表中每个位置都是一个长为 2 2 2的字符串数组,规定数组内的字符串是”相似的“。再给定两个字符串数组,问这两个数组是否对应位置的字符串都相似。规定”相似关系“是个等价关系。如果两个数组长度不等则直接返回false;并且如果对应位置上的字符串相等,也视为相似,不必含在列表里。
思路是并查集。先用一个哈希表将pair里的单词与一个整数进行对应。如果遍历到一个pair的时候两个字符串已经在哈希表里,则执行并查集的union操作;如果只有一个在哈希表里,则将那个不在哈希表里的字符串与在的那个对应相同的数字;如果两个都不在哈希表里,则将这两个字符串都加进哈希表里,并对应相等的数字。代码如下:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
class UnionFind {
int[] parent, rank;
UnionFind(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
}
}
public int find(int p) {
if (p != parent[p]) {
parent[p] = find(parent[p]);
}
return parent[p];
}
public void union(int p, int q) {
int pRoot = find(p), qRoot = find(q);
if (rank[pRoot] < rank[qRoot]) {
parent[pRoot] = qRoot;
} else if (rank[pRoot] > rank[qRoot]) {
parent[qRoot] = pRoot;
} else {
parent[pRoot] = qRoot;
rank[qRoot]++;
}
}
}
public boolean areSentencesSimilarTwo(String[] words1, String[] words2, List<List<String>> pairs) {
if (words1.length != words2.length) {
return false;
}
UnionFind uf = new UnionFind(pairs.size());
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < pairs.size(); i++) {
String s1 = pairs.get(i).get(0), s2 = pairs.get(i).get(1);
// 如果哈希表里含有两个字符串,则并查集将对应的两个整数union起来;
// 如果只含其中一个,就把不含的那个对应的数字设为含的那个对应的数字;
// 如果都不含,就直接对应一个相等的整数
if (map.containsKey(s1) && map.containsKey(s2)) {
uf.union(map.get(s1), map.get(s2));
} else if (!map.containsKey(s1) && !map.containsKey(s2)) {
map.put(s1, i);
map.put(s2, i);
} else if (map.containsKey(s1)) {
map.put(s2, map.get(s1));
} else {
map.put(s1, map.get(s2));
}
}
for (int i = 0; i < words1.length; i++) {
String s1 = words1[i], s2 = words2[i];
// 特判一下相等的情况
if (s1.equals(s2)) {
continue;
}
// 如果不含,则直接返回false
if (!map.containsKey(s1) || !map.containsKey(s2)) {
return false;
}
// 否则看一下是否同属同一个集合
if (uf.find(map.get(s1)) != uf.find(map.get(s2))) {
return false;
}
}
return true;
}
}
时空复杂度 O ( n l ) O(nl) O(nl)。