mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-29 21:14:35 +08:00
formatting source-code for d7af6fdc8c
This commit is contained in:
@@ -26,14 +26,17 @@
|
||||
* \param[in] pattern text for which to create the partial match table
|
||||
* \returns the partial match table as a vector array
|
||||
*/
|
||||
std::vector<int> getFailureArray(const std::string &pattern) {
|
||||
std::vector<int> getFailureArray(const std::string &pattern)
|
||||
{
|
||||
int pattern_length = pattern.size();
|
||||
std::vector<int> failure(pattern_length + 1);
|
||||
failure[0] = -1;
|
||||
int j = -1;
|
||||
|
||||
for (int i = 0; i < pattern_length; i++) {
|
||||
while (j != -1 && pattern[j] != pattern[i]) {
|
||||
for (int i = 0; i < pattern_length; i++)
|
||||
{
|
||||
while (j != -1 && pattern[j] != pattern[i])
|
||||
{
|
||||
j = failure[j];
|
||||
}
|
||||
j++;
|
||||
@@ -49,13 +52,16 @@ std::vector<int> getFailureArray(const std::string &pattern) {
|
||||
* \returns `true` if pattern was found
|
||||
* \returns `false` if pattern was not found
|
||||
*/
|
||||
bool kmp(const std::string &pattern, const std::string &text) {
|
||||
bool kmp(const std::string &pattern, const std::string &text)
|
||||
{
|
||||
int text_length = text.size(), pattern_length = pattern.size();
|
||||
std::vector<int> failure = getFailureArray(pattern);
|
||||
|
||||
int k = 0;
|
||||
for (int j = 0; j < text_length; j++) {
|
||||
while (k != -1 && pattern[k] != text[j]) {
|
||||
for (int j = 0; j < text_length; j++)
|
||||
{
|
||||
while (k != -1 && pattern[k] != text[j])
|
||||
{
|
||||
k = failure[k];
|
||||
}
|
||||
k++;
|
||||
@@ -66,21 +72,28 @@ bool kmp(const std::string &pattern, const std::string &text) {
|
||||
}
|
||||
|
||||
/** Main function */
|
||||
int main() {
|
||||
int main()
|
||||
{
|
||||
std::string text = "alskfjaldsabc1abc1abc12k23adsfabcabc";
|
||||
std::string pattern = "abc1abc12l";
|
||||
|
||||
if (kmp(pattern, text) == true) {
|
||||
if (kmp(pattern, text) == true)
|
||||
{
|
||||
std::cout << "Found" << std::endl;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Not Found" << std::endl;
|
||||
}
|
||||
|
||||
text = "abcabc";
|
||||
pattern = "bca";
|
||||
if (kmp(pattern, text) == true) {
|
||||
if (kmp(pattern, text) == true)
|
||||
{
|
||||
std::cout << "Found" << std::endl;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Not Found" << std::endl;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user