Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Contribute to GitLab
Sign in
Toggle navigation
P
pdp-camp
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Merge Requests
0
Merge Requests
0
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Commits
Open sidebar
Public
pdp-camp
Commits
0d52e0ee
Commit
0d52e0ee
authored
May 09, 2017
by
Panagiotis Kostopanagiotis
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
KMP Pattern-Matching
parent
4dbfe528
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
71 additions
and
0 deletions
+71
-0
kmp.cpp
2017/kmp.cpp
+71
-0
No files found.
2017/kmp.cpp
0 → 100644
View file @
0d52e0ee
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAXN 1000010
using
namespace
std
;
int
P
[
MAXN
+
1
];
void
prefix
(
char
pattern
[]
)
{
int
N
=
strlen
(
pattern
);
P
[
0
]
=
-
1
;
for
(
int
i
=
1
;
i
<
N
;
i
++
)
{
int
j
=
P
[
i
-
1
];
while
(
true
)
{
if
(
pattern
[
i
]
==
pattern
[
j
+
1
]
)
{
P
[
i
]
=
j
+
1
;
break
;
}
else
if
(
j
==
-
1
)
{
P
[
i
]
=
-
1
;
break
;
}
else
{
j
=
P
[
j
];
}
}
}
}
int
KMP
(
char
text
[],
char
pattern
[]
)
{
int
i
=
0
,
j
=
0
,
N
=
strlen
(
text
),
M
=
strlen
(
pattern
);
prefix
(
pattern
);
while
(
true
)
{
if
(
i
==
N
)
{
break
;
}
if
(
text
[
i
]
==
pattern
[
j
]
)
{
if
(
j
==
M
-
1
)
{
return
i
-
M
;
}
i
++
;
j
++
;
}
else
if
(
j
==
0
)
{
i
++
;
}
else
{
j
=
P
[
j
];
}
}
return
0
;
}
int
main
(
void
)
{
char
text
[
MAXN
+
1
],
pattern
[
MAXN
+
1
];
scanf
(
"%s%s"
,
text
,
pattern
);
int
res
=
KMP
(
text
,
pattern
);
if
(
res
)
{
printf
(
"%s occurs in %s with shift %d
\n
"
,
pattern
,
text
,
res
+
1
);
}
else
{
printf
(
"%s does not occur in %s
\n
"
,
pattern
,
text
);
}
return
0
;
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment