|
| 1 | +// |
| 2 | +// algorithm - some algorithms in "Introduction to Algorithms", third edition |
| 3 | +// Copyright (C) 2018 lxylxy123456 |
| 4 | +// |
| 5 | +// This program is free software: you can redistribute it and/or modify |
| 6 | +// it under the terms of the GNU Affero General Public License as |
| 7 | +// published by the Free Software Foundation, either version 3 of the |
| 8 | +// License, or (at your option) any later version. |
| 9 | +// |
| 10 | +// This program is distributed in the hope that it will be useful, |
| 11 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +// GNU Affero General Public License for more details. |
| 14 | +// |
| 15 | +// You should have received a copy of the GNU Affero General Public License |
| 16 | +// along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 17 | +// |
| 18 | + |
| 19 | +#ifndef MAIN |
| 20 | +#define MAIN |
| 21 | +#define MAIN_NaiveStringMatcher |
| 22 | +#endif |
| 23 | + |
| 24 | +#ifndef FUNC_NaiveStringMatcher |
| 25 | +#define FUNC_NaiveStringMatcher |
| 26 | + |
| 27 | +#include "utils.h" |
| 28 | + |
| 29 | +template <typename T> |
| 30 | +bool equal(const std::vector<T>& S, size_t Ss, |
| 31 | + const std::vector<T>& P, size_t Ps, size_t n) { |
| 32 | + for (size_t i = 0; i < n; i++) |
| 33 | + if (S[Ss + i] != P[Ps + i]) |
| 34 | + return false; |
| 35 | + return true; |
| 36 | +} |
| 37 | + |
| 38 | +template <typename T> |
| 39 | +bool equal(const std::vector<T>& S, size_t Ss, size_t Se, |
| 40 | + const std::vector<T>& P, size_t Ps, size_t Pe) { |
| 41 | + size_t n = Se - Ss; |
| 42 | + if (n != Pe - Ps) |
| 43 | + return false; |
| 44 | + return equal(S, P, Ss, Ps, n); |
| 45 | +} |
| 46 | + |
| 47 | +template <typename T> |
| 48 | +void NaiveStringMatcher(const std::vector<T>& S, const std::vector<T>& P, |
| 49 | + std::vector<size_t>& ans) { |
| 50 | + size_t n = S.size(), m = P.size(); |
| 51 | + for (size_t s = 0; s <= n - m; s++) |
| 52 | + if (equal(P, 0, S, s, m)) |
| 53 | + ans.push_back(s); |
| 54 | +} |
| 55 | +#endif |
| 56 | + |
| 57 | +#ifdef MAIN_NaiveStringMatcher |
| 58 | +int main(int argc, char *argv[]) { |
| 59 | + const size_t n = get_argv(argc, argv, 1, 40); |
| 60 | + const size_t m = get_argv(argc, argv, 2, 3); |
| 61 | + const size_t s = get_argv(argc, argv, 3, 2); |
| 62 | + std::vector<char> S, P; |
| 63 | + random_integers<char>(S, 'a', 'a' + s, n); |
| 64 | + random_integers<char>(P, 'a', 'a' + s, m); |
| 65 | + output_integers(S, ""); |
| 66 | + output_integers(P, ""); |
| 67 | + std::vector<size_t> ans; |
| 68 | + NaiveStringMatcher(S, P, ans); |
| 69 | + output_integers(ans); |
| 70 | + return 0; |
| 71 | +} |
| 72 | +#endif |
| 73 | + |
0 commit comments