Shiyan12

БМ-поиск

Dec 12th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4. #include <windows.h>
  5.  
  6. using namespace std;
  7.  
  8. int bauermooresearch(string& s, string& p) {
  9.     int m = p.length();
  10.     map <char, int> t;
  11.     for (int i = 0; i < m - 1; ++i)
  12.         t[p[i]] = m - 1 - i;
  13.     int i = m - 1, j = m - 1;
  14.     int n = s.length();
  15.     while (i < n)
  16.         if (p[j] == s[i]) {
  17.             if (j == 0)
  18.                 return i;
  19.             --j;
  20.             --i;
  21.         } else {
  22.             if (t.find(s[i]) != t.end())
  23.                 i += t[s[i]];
  24.             else
  25.                 i += m;
  26.             j = m - 1;
  27.         }
  28.     return -1;
  29. }
  30.  
  31. int main() {
  32.     SetConsoleCP(1251);
  33.     SetConsoleOutputCP(1251);
  34.     string p, s;
  35.     cout << "Текст: ";
  36.     getline(cin, s);
  37.     cout << "Строка: ";
  38.     getline(cin, p);
  39.     int ans = bauermooresearch(s, p);
  40.     if (ans == -1)
  41.         cout << "Строка в тексте не найдена!" << endl;
  42.     else
  43.         cout << "Позиция первого вхождения строки в текст: " << ans << "." << endl;
  44.     system("pause");
  45.     return 0;
  46. }
Add Comment
Please, Sign In to add comment