1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
strings-differ-by-one-character.cpp 1.29 KB
一键复制 编辑 原始数据 按行查看 历史
// 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;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助