FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm-examples/cpp-algorithm/src/string/rabin_karp.cpp at main · codejsha/algorithm-examples · GitHub
codejsha
/
algorithm-examples
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
2
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm-examples
/
cpp-algorithm
/
src
/
string
/
rabin_karp.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
70 lines (59 loc) · 1.78 KB
Breadcrumbs
algorithm-examples
/
cpp-algorithm
/
src
/
string
/
rabin_karp.cpp
Copy path
File metadata and controls
70 lines (59 loc) · 1.78 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#
include
"
rabin_karp.h
"
auto
RabinKarp::RabinKarpMatcher1
(
const
std::string& text,
const
std::string& pattern) -> std::vector<int>
{
std::vector<
int
> result;
if
(text.
size
() < pattern.
size
())
{
return
result;
}
const
size_t
pattern_hash = std::hash<std::string>{}(pattern);
for
(
int
i =
0
; i <=
static_cast
<
int
>(text.
size
()) -
static_cast
<
int
>(pattern.
size
()); ++i)
{
const
size_t
next_hash = std::hash<std::string>{}(text.
substr
(i, pattern.
size
()));
if
(next_hash == pattern_hash && text.
substr
(i, pattern.
size
()) == pattern)
{
result.
emplace_back
(i);
}
}
return
result;
}
auto
RabinKarp::RabinKarpMatcher2
(
const
std::string& text,
const
std::string& pattern) -> std::vector<int>
{
std::vector<
int
> result;
if
(text.
size
() < pattern.
size
())
{
return
result;
}
constexpr
int
base =
256
;
constexpr
int
prime =
101
;
int
pattern_hash =
0
;
for
(
const
char
ch : pattern)
{
pattern_hash = (base * pattern_hash + ch) % prime;
}
for
(
int
i =
0
; i <=
static_cast
<
int
>(text.
size
()) -
static_cast
<
int
>(pattern.
size
()); ++i)
{
int
next_hash =
0
;
for
(
int
j =
0
; j <
static_cast
<
int
>(pattern.
size
()); ++j)
{
next_hash = (base * next_hash + text[i + j]) % prime;
}
if
(pattern_hash == next_hash)
{
bool
is_match =
true
;
for
(
int
j =
0
; j <
static_cast
<
int
>(pattern.
size
()); ++j)
{
if
(text[i + j] != pattern[j])
{
is_match =
false
;
break
;
}
}
if
(is_match)
{
result.
emplace_back
(i);
}
}
}
return
result;
}
Back
|
FazBrowse Home
|
New Git URL