代码拉取完成,页面将自动刷新
// 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;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。