-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsentence-similarity.cpp
73 lines (56 loc) · 1.3 KB
/
sentence-similarity.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* Copyright (c) 2018 Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
// https://leetcode.com/problems/sentence-similarity/
class Solution {
public:
using ums = unordered_map<string, unordered_set<string>>;
bool areSentencesSimilar(vector<string> &words1, vector<string> &words2,
vector<vector<string>> &pairs) {
if (words1.size() != words2.size()) {
return false;
}
ums to;
for (auto &p : pairs) {
if (p[0] == p[1]) {
continue;
}
to[p[0]].insert(p[1]);
to[p[1]].insert(p[0]);
}
for (size_t i = 0, N = words1.size(); i < N; ++i) {
if (!similar(words1[i], words2[i], to)) {
return false;
}
}
return true;
}
bool similar(const string &w1, const string &w2, const ums &to) {
if (w1 == w2) {
return true;
}
if (directMapping(w1, w2, to)) {
return true;
}
return false;
}
bool directMapping(const string &w1, const string &w2, const ums &to) {
auto it1 = to.find(w1);
if (to.end() == it1) {
return false;
}
for (auto &s1 : it1->second) {
if (w2 == s1) {
return true;
}
}
return false;
}
};