Given two sentences words1, words2
(each represented as an array of strings), and a list of similar word pairs pairs
, determine if two sentences are similar.
For example, words1 = ["great", "acting", "skills"]
and words2 = ["fine", "drama", "talent"]
are similar, if the similar word pairs arepairs = [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]]
.
Note that the similarity relation is transitive. 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 sentences words1 = ["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 like words1 = ["great"]
can never be similar towords2 = ["doubleplus","good"]
.
这道题题目大意是给定一个相似的单词对序列, 并且这种相似性有传递性(这句话是个很明显的提示, 需要进行合并操作)。 然后给出两个单词向量, 问是否这两个向量每对都是相似的。
基本思路: 根据相似单词对列表建立并查集,建立完成之后扫描两个单词向量, 看每一对是否都在一个相似域中。(即每一对单词的根是否一致)
这里有个小trick : 按照题目直接进行并查集建立, 需要一个map[string, string]
.但是, 如果预先把单词利用一个map[string, int]
做一个映射, 那么 我们需要处理的又是一个最简单的并查集了。
struct UF {
UF(int n) {
father.resize(n + 1);
for (int i = 0; i < father.size(); ++i) {
father[i] = i;
}
}
bool Union(int a, int b) {
int root1 = Find(a), root2 = Find(b);
if (root1 != root2) {
father[root2] = root1; //or father[root1] = root2;
return true;
}
return false;
}
int Find(int k) {
int i = k, j = k;
while (i != father[i]) i = father[i]; // i is the root of k.
//path comdense (to be continued)
while (j != father[j]) {
int tmp = father[j];
father[j] = i;
j = tmp;
}
return i;
}
vector<int> father;
};
class Solution {
public:
bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {
if (words1.size() != words2.size()) return false;
unordered_map<string, int> index;
int count = 0;
for (int i = 0; i < pairs.size(); ++i) {
if (index[pairs[i].first] == 0) {
++count;
index[pairs[i].first] = count;
}
if (index[pairs[i].second] == 0) {
++count;
index[pairs[i].second] = count;
}
}
UF uf_set(count);
for (int i = 0; i < pairs.size(); ++i) {
uf_set.Union(index[pairs[i].first], index[pairs[i].second]);
}
for (int i = 0; i < words1.size(); ++i) {
if (words1[i] == words2[i]) continue;
int root1 = uf_set.Find(index[words1[i]]), root2 = uf_set.Find(index[words2[i]]);
if (root1 == 0 || root2 == 0 || root1 != root2) return false;
}
return true;
}
};