737 Sentence Similarity II

1. Question

Given two sentenceswords1, words2(each represented as an array of strings), and a list of similar word pairspairs, determine if two sentences are similar.
For example,words1 = ["great", "acting", "skills"]andwords2 = ["fine", "drama", "talent"]are similar, if the similar word pairs arepairs = [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]].
Note that the similarity relationistransitive. For example, if "great" and "good" are similar, and "fine" and "good" are similar, then "great" and "fine" are similar.
Similarity is also symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.
Also, a word is always similar with itself. For example, the sentenceswords1 = ["great"], words2 = ["great"], pairs = []are similar, even though there are no specified similar word pairs.
Finally, sentences can only be similar if they have the same number of words. So a sentence likewords1 = ["great"]can never be similar towords2 = ["doubleplus","good"].
Note:
The length ofwords1andwords2will not exceed1000.
The length ofpairswill not exceed2000.
The length of eachpairs[i]will be2.
The length of eachwords[i]andpairs[i][j]will be in the range[1, 20].

2. Implementation

(1) DFS
1
class Solution {
2
public boolean areSentencesSimilarTwo(String[] words1, String[] words2, String[][] pairs) {
3
if (words1.length != words2.length) {
4
return false;
5
}
6
7
Map<String, Set<String>> graph = new HashMap<>();
8
9
for (String[] pair : pairs) {
10
graph.putIfAbsent(pair[0], new HashSet<>());
11
graph.putIfAbsent(pair[1], new HashSet<>());
12
13
graph.get(pair[0]).add(pair[1]);
14
graph.get(pair[1]).add(pair[0]);
15
}
16
17
for (int i = 0; i < words1.length; i++) {
18
if (words1[i].equals(words2[i])) {
19
continue;
20
}
21
22
if (!graph.containsKey(words1[i]) || !graph.containsKey(words2[i])) {
23
return false;
24
}
25
Set<String> visited = new HashSet<>();
26
27
if (!dfs(words1[i], words2[i], graph, visited)) {
28
return false;
29
}
30
}
31
return true;
32
}
33
34
public boolean dfs(String startWord, String endWord, Map<String, Set<String>> graph, Set<String> visited) {
35
if (graph.get(startWord).contains(endWord)) {
36
return true;
37
}
38
39
if (visited.contains(startWord)) {
40
return false;
41
}
42
43
visited.add(startWord);
44
for (String nextWord : graph.get(startWord)) {
45
if (dfs(nextWord, endWord, graph, visited)) {
46
return true;
47
}
48
}
49
return false;
50
}
51
}
Copied!
(2) Union Find
思路:
(1) 用union find的关键就是要给每个pair里的word分配一个unique id,然后用map存string到id的关系
(2) 在遍历words1和words2,如果map里面没有words1或words2当前的词或者通过find我们发现当前word1和word2不在一个集合里,return false
1
class Solution {
2
public boolean areSentencesSimilarTwo(String[] words1, String[] words2, String[][] pairs) {
3
if (words1.length != words2.length) {
4
return false;
5
}
6
7
UnionFind uf = new UnionFind(2 * pairs.length);
8
9
Map<String, Integer> map = new HashMap<>();
10
int id = 0;
11
12
for (String[] pair : pairs) {
13
for (String word : pair) {
14
if (!map.containsKey(word)) {
15
map.put(word, id);
16
++id;
17
}
18
}
19
20
uf.union(map.get(pair[0]), map.get(pair[1]));
21
}
22
23
24
for (int i = 0; i < words1.length; i++) {
25
String word1 = words1[i];
26
String word2 = words2[i];
27
28
if (word1.equals(word2)) {
29
continue;
30
}
31
32
if (!map.containsKey(word1) || !map.containsKey(word2) || uf.find(map.get(word1)) != uf.find(map.get(word2))) {
33
return false;
34
}
35
}
36
return true;
37
}
38
39
class UnionFind {
40
int[] sets;
41
int[] size;
42
int count;
43
44
public UnionFind(int n) {
45
sets = new int[n];
46
size = new int[n];
47
count = n;
48
49
for (int i = 0; i < n; i++) {
50
sets[i] = i;
51
size[i] = 1;
52
}
53
}
54
55
public int find(int node) {
56
while (node != sets[node]) {
57
node = sets[node];
58
}
59
return node;
60
}
61
62
public void union(int i, int j) {
63
int node1 = find(i);
64
int node2 = find(j);
65
66
if (node1 == node2) {
67
return;
68
}
69
70
if (size[node1] < size[node2]) {
71
sets[node1] = node2;
72
size[node2] += size[node1];
73
}
74
else {
75
sets[node2] = node1;
76
size[node1] += size[node2];
77
}
78
--count;
79
}
80
}
81
}
Copied!

3. Time & Space Complexity

DFS: 时间复杂度O(nk), 其中n为words的长度, k为pairs的长度,空间复杂度O(k)
Union Find: 时间复杂度O(k + n), 空间复杂度O(k)