Skip to content

Commit ed9adcd

Browse files
authored
Create words-within-two-edits-of-dictionary.cpp
1 parent 2b18a52 commit ed9adcd

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// Time: O(25 * l * (n + q))
2+
// Space: O(25 * l * n)
3+
4+
// hash
5+
class Solution {
6+
public:
7+
vector<string> twoEditWords(vector<string>& queries, vector<string>& dictionary) {
8+
static const uint64_t MOD = (1ull << 64) - 59; // largest 64-bit prime
9+
static const uint64_t BASE = 113;
10+
vector<uint64_t> POW = {1};
11+
const auto& add = [](uint64_t a, uint64_t b) {
12+
if (MOD - a <= b) {
13+
b -= MOD; // relied on unsigned integer overflow in order to give the expected results
14+
}
15+
return a + b;
16+
};
17+
const auto& sub = [&](uint64_t a, uint64_t b) {
18+
return add(a, MOD - b);
19+
};
20+
const auto& mult = [&](uint64_t a, uint64_t b) {
21+
uint64_t result = 0;
22+
if (a < b) {
23+
swap(a, b);
24+
}
25+
while (b > 0) {
26+
if (b % 2 == 1) {
27+
result = add(result, a);
28+
}
29+
a = add(a, a);
30+
b /= 2;
31+
}
32+
return result;
33+
};
34+
const auto& pow = [&](int i) {
35+
while (!(i < size(POW))) {
36+
POW.emplace_back(mult(POW.back(), BASE));
37+
}
38+
return POW[i];
39+
};
40+
41+
unordered_set<uint64_t> lookup;
42+
for (const auto& w : dictionary) {
43+
uint64_t h = 0;
44+
for (int i = 0; i < size(w); ++i) {
45+
h = add(h, mult(sub(w[i], 'a'), pow(i)));
46+
}
47+
for (int i = 0; i < size(w); ++i) {
48+
for (char x = 'a'; x <= 'z'; ++x) {
49+
if (x == w[i]) {
50+
continue;
51+
}
52+
lookup.emplace(add(h, mult(sub(x, w[i]), pow(i))));
53+
}
54+
}
55+
}
56+
vector<string> result;
57+
for (const auto& w : queries) {
58+
uint64_t h = 0;
59+
for (int i = 0; i < size(w); ++i) {
60+
h = add(h, mult(sub(w[i], 'a'), pow(i)));
61+
}
62+
for (int i = 0; i < size(w); ++i) {
63+
char x = 'a';
64+
for (; x <= 'z'; ++x) {
65+
if (x == w[i]) {
66+
continue;
67+
}
68+
if (lookup.count(add(h, mult(sub(x, w[i]), pow(i))))) {
69+
break;
70+
}
71+
}
72+
if (x <= 'z') {
73+
result.emplace_back(w);
74+
break;
75+
}
76+
}
77+
}
78+
return result;
79+
}
80+
};
81+
82+
// Time: O(q * n * l)
83+
// Space: O(1)
84+
// brute force
85+
class Solution2 {
86+
public:
87+
vector<string> twoEditWords(vector<string>& queries, vector<string>& dictionary) {
88+
const auto& check = [&](const auto& w1, const auto& w2) {
89+
int cnt = 0;
90+
for (int i = 0; i < size(w1); ++i) {
91+
cnt += static_cast<int>(w1[i] != w2[i]);
92+
}
93+
return cnt <= 2;
94+
};
95+
96+
vector<string> result;
97+
for (const auto& q : queries) {
98+
for (const auto& d : dictionary) {
99+
if (check(q, d)) {
100+
result.emplace_back(q);
101+
break;
102+
}
103+
}
104+
}
105+
return result;
106+
}
107+
};

0 commit comments

Comments
 (0)