账号合并
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
// 直接用mail作并查集的键,同用户的mail在同一集合
unordered_map<string, string> parent;
unordered_map<string, string> owner;
for (auto &account : accounts) {
for (int i = 1; i < account.size(); i++) {
auto &mail = account[i];
parent[mail] = mail; // init
owner[mail] = account[0];
}
}
for (auto &account : accounts) {
auto px = find(account[1], parent);
for (int i = 2; i < account.size(); i++) {
auto py = find(account[i], parent);
if (px != py) parent[py] = px; // unite
}
}
// 同一集合的mail放入数组
unordered_map<string, vector<string>> mp;
for (auto &e : parent) {
auto &x = e.first;
auto px = find(e.second, parent);
mp[px].push_back(x);
}
vector<vector<string>> ans;
for (auto &e : mp) {
auto &mails = e.second;
sort(mails.begin(), mails.end());
mails.insert(mails.begin(), owner[e.first]);
ans.push_back(mails);
}
return ans;
}
string find(const string &mail, unordered_map<string, string> &parent) {
if (parent[mail] != mail)
parent[mail] = find(parent[mail], parent);
return parent[mail];
}
两句子相似
Given two sentences
words1, 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 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"].Note:
- The length of
words1andwords2will not exceed1000.- The length of
pairswill not exceed2000.- The length of each
pairs[i]will be2.- The length of each
words[i]andpairs[i][j]will be in the range[1, 20].
bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {
if (words1.size() != words2.size()) return false;
// 直接用word作并查集的键
unordered_map<string, string> parent;
for (auto &p : pairs) {
auto pw1 = find(p.first, parent), pw2 = find(p.second, parent);
if (pw1 != pw2) parent[pw1] = pw2; // unite
}
for (int i = 0; i < words1.size(); i++) {
auto &w1 = words1[i], &w2 = words2[i];
if (w1 != w2 && find(w1, parent) != find(w2, parent)) return false;
}
return true;
}
string find(const string &s, unordered_map<string, string> &parent) {
if (!parent.count(s)) parent[s] = s;
if (parent[s] != s)
parent[s] = find(parent[s], parent);
return parent[s];
}