Rabin-Karp算法
不断地移动窗口,生成Hash来对其匹配。时间复杂度为O(|dictory|+n2)
H
a
s
h
(
c
)
=
(
c
1
×
b
m
−
1
+
c
2
×
b
m
−
2
+
c
3
×
b
m
−
3
+
.
.
.
+
c
m
×
b
0
)
m
o
d
h
Hash(c)=(c_1\times b^{m-1} + c_2\times b^{m-2} + c_3\times b^{m-3}+...+c_m\times b^{0}) \mod h
Hash(c)=(c1×bm−1+c2×bm−2+c3×bm−3+...+cm×b0)modh
递归模式:
H
a
s
h
n
(
c
)
=
H
a
s
h
n
−
1
(
c
)
∗
b
+
c
n
m
o
d
h
Hash_n(c)=Hash_{n-1}(c)*b + c_n \mod h
Hashn(c)=Hashn−1(c)∗b+cnmodh
其中b和h互质,且均为素常数(1<b<h)
这里注意的地方是s[i]-'a’必须+1。
代码如下:
#define PMOD 1000000007
#define BASE 41
#define LL long long
#define maxn 1005
int ans[maxn];
class Solution {
public:
int respace(vector<string>& dictionary, string sentence) {
int i, j;
int dn = dictionary.size();
const string* ds = dictionary.data();
unordered_set<int> sets=unordered_set<int>(dn);
int t;
for (i = 0; i < dn; i++)
{
t = 0;
int dss = ds[i].size();
const char* dsc = ds[i].c_str();
for (j = 0; j < dss; j++)
{
t = (((LL)t) * BASE + (dsc[j] - 'a'+1)) % PMOD;
}
sets.insert(t);
}
const char* sen = sentence.c_str();
int senl = sentence.size();
for (i = 0; i <= senl; i++)
ans[i] = i;
for (i = 0; i < senl; i++)
{
t = 0;
for (j = i; j < senl; j++)
{
ans[j + 1] = min(ans[j] + 1,ans[j+1]);
t = (((LL)t) * BASE + (sen[j] - 'a'+1)) % PMOD;
if (sets.find(t) != sets.end())
{
ans[j+1] = min(ans[j+1], ans[i]);
}
}
}
return ans[senl];
}
};