Skip to content

Commit a47718f

Browse files
authored
Create strings-differ-by-one-character.cpp
1 parent 023c10d commit a47718f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time: O(n * m)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
bool differByOne(vector<string>& dict) {
7+
static const int MOD = 1e9 + 7;
8+
static const int64_t P = 113;
9+
10+
vector<int> hashes(dict.size());
11+
for (int i = 0; i < dict.size(); ++i) {
12+
for (const auto& c : dict[i]) {
13+
hashes[i] = (P * hashes[i] + (c - 'a')) % MOD;
14+
}
15+
}
16+
17+
int64_t base = 1;
18+
for (int p = dict[0].length() - 1; p >= 0; --p) {
19+
unordered_map<int, vector<int>> lookup;
20+
for (int i = 0; i < dict.size(); ++i) {
21+
int new_hash = ((hashes[i] - base * (dict[i][p] - 'a') % MOD) + MOD) % MOD;
22+
if (lookup.count(new_hash)) {
23+
auto target = dict[i].substr(0, p);
24+
target += dict[i].substr(p + 1);
25+
for (const auto& j : lookup[new_hash]) {
26+
auto candidate = dict[j].substr(0, p);
27+
candidate += dict[j].substr(p + 1);
28+
if (candidate == target) {
29+
return true;
30+
}
31+
}
32+
}
33+
lookup[new_hash].emplace_back(i);
34+
}
35+
base = (P * base) % MOD;
36+
}
37+
return false;
38+
}
39+
};

0 commit comments

Comments
 (0)