2020-05-29 20:00:58 +08:00
|
|
|
/**
|
|
|
|
* @file
|
|
|
|
* @brief String pattern search - brute force
|
|
|
|
*/
|
|
|
|
#include <iostream>
|
|
|
|
#ifdef _MSC_VER
|
|
|
|
#include <string> // use this for MS Visucal C++
|
|
|
|
#else
|
|
|
|
#include <cstring>
|
|
|
|
#endif
|
|
|
|
#include <vector>
|
2020-04-16 18:32:46 +08:00
|
|
|
|
2020-05-29 20:00:58 +08:00
|
|
|
/**
|
|
|
|
* Find a pattern in a string by comparing the pattern to every substring.
|
|
|
|
* @param text Any string that might contain the pattern.
|
|
|
|
* @param pattern String that we are searching for.
|
|
|
|
* @return Index where the pattern starts in the text
|
|
|
|
* @return -1 if the pattern was not found.
|
|
|
|
*/
|
2020-05-30 07:26:30 +08:00
|
|
|
int brute_force(const std::string &text, const std::string &pattern)
|
|
|
|
{
|
2020-05-29 20:00:58 +08:00
|
|
|
size_t pat_l = pattern.length();
|
|
|
|
size_t txt_l = text.length();
|
|
|
|
int index = -1;
|
2020-05-30 07:26:30 +08:00
|
|
|
if (pat_l <= txt_l)
|
|
|
|
{
|
|
|
|
for (size_t i = 0; i < txt_l - pat_l + 1; i++)
|
|
|
|
{
|
2020-05-29 20:00:58 +08:00
|
|
|
std::string s = text.substr(i, pat_l);
|
2020-05-30 07:26:30 +08:00
|
|
|
if (s == pattern)
|
|
|
|
{
|
2020-05-29 20:00:58 +08:00
|
|
|
index = i;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return index;
|
|
|
|
}
|
2020-04-16 18:32:46 +08:00
|
|
|
|
2020-05-29 20:00:58 +08:00
|
|
|
/** set of test cases */
|
|
|
|
const std::vector<std::vector<std::string>> test_set = {
|
2020-04-16 18:32:46 +08:00
|
|
|
// {text, pattern, expected output}
|
2020-05-29 20:00:58 +08:00
|
|
|
{"a", "aa", "-1"}, {"a", "a", "0"}, {"ba", "b", "0"},
|
|
|
|
{"bba", "bb", "0"}, {"bbca", "c", "2"}, {"ab", "b", "1"}};
|
2020-04-16 18:32:46 +08:00
|
|
|
|
2020-05-29 20:00:58 +08:00
|
|
|
/** Main function */
|
2020-05-30 07:26:30 +08:00
|
|
|
int main()
|
|
|
|
{
|
|
|
|
for (size_t i = 0; i < test_set.size(); i++)
|
|
|
|
{
|
2020-05-29 20:00:58 +08:00
|
|
|
int output = brute_force(test_set[i][0], test_set[i][1]);
|
|
|
|
|
|
|
|
if (std::to_string(output) == test_set[i][2])
|
|
|
|
std::cout << "success\n";
|
2020-04-16 18:32:46 +08:00
|
|
|
else
|
2020-05-29 20:00:58 +08:00
|
|
|
std::cout << "failure\n";
|
2020-04-16 18:32:46 +08:00
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|