forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
strings-differ-by-one-character.cpp
39 lines (36 loc) · 1.29 KB
/
strings-differ-by-one-character.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
// Time: O(n * m)
// Space: O(n)
class Solution {
public:
bool differByOne(vector<string>& dict) {
static const int MOD = 1e9 + 7;
static const int64_t P = 113;
vector<int> hashes(dict.size());
for (int i = 0; i < dict.size(); ++i) {
for (const auto& c : dict[i]) {
hashes[i] = (P * hashes[i] + (c - 'a')) % MOD;
}
}
int64_t base = 1;
for (int p = dict[0].length() - 1; p >= 0; --p) {
unordered_map<int, vector<int>> lookup;
for (int i = 0; i < dict.size(); ++i) {
int new_hash = ((hashes[i] - base * (dict[i][p] - 'a') % MOD) + MOD) % MOD;
if (lookup.count(new_hash)) {
auto target = dict[i].substr(0, p);
target += dict[i].substr(p + 1);
for (const auto& j : lookup[new_hash]) {
auto candidate = dict[j].substr(0, p);
candidate += dict[j].substr(p + 1);
if (candidate == target) {
return true;
}
}
}
lookup[new_hash].emplace_back(i);
}
base = (P * base) % MOD;
}
return false;
}
};