Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
repeated-string-match.cpp 1.80 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2017-10-02 20:19 +08:00 . rename repeated-string-matc.cpp
// Time: O(n + m)
// Space: O(1)
// Rabin-Karp Algorithm (rolling hash)
class Solution {
public:
int repeatedStringMatch(string A, string B) {
static const uint64_t M = 1000000007;
static const uint64_t p = 113;
static const uint64_t p_inv = pow(p, M - 2, M);
const auto q = (B.length() + A.length() - 1) / A.length();
uint64_t b_hash = 0, power = 1;
for (int i = 0; i < B.length(); ++i) {
b_hash += power * B[i];
b_hash %= M;
power = (power * p) % M;
}
uint64_t a_hash = 0; power = 1;
for (int i = 0; i < B.length(); ++i) {
a_hash += power * A[i % A.length()];
a_hash %= M;
power = (power * p) % M;
}
if (a_hash == b_hash && check(0, A, B)) {
return q;
}
power = (power * p_inv) % M;
for (int i = B.length(); i < (q + 1) * A.length(); ++i) {
a_hash -= A[(i - B.length()) % A.length()];
a_hash *= p_inv;
a_hash += power * A[i % A.length()];
a_hash %= M;
if (a_hash == b_hash && check(i - B.length() + 1, A, B)) {
return i < q * A.length() ? q : q + 1;
}
}
return -1;
}
private:
bool check(int index, const string& A, const string& B) {
for (int i = 0; i < B.length(); ++i) {
if (A[(i + index) % A.length()] != B[i]) {
return false;
}
}
return true;
}
uint64_t pow(uint64_t a,uint64_t b, uint64_t m) {
a %= m;
uint64_t result = 1;
while (b) {
if (b & 1) {
result = (result * a) % m;
}
a = (a * a) % m;
b >>= 1;
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助