Advertisement
AmidamaruZXC

Untitled

Feb 17th, 2020
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <vector>
  5. #include <stdlib.h>
  6.  
  7. using namespace std;
  8.  
  9. //Основная задача - реализовать данный метод
  10. //Можно изменить передачу параметров на ссылки (&)
  11. //Можно добавлять любое количество любых вспомогательных методов, структур и классов
  12. void getSubstrings(string& source, string& substring, vector<int>& res)
  13. {
  14.     int n = substring.length(), i, t, position = 0;
  15.  
  16.     int* borderArray = new int[n];
  17.     borderArray[0] = 0;
  18.  
  19.     for (i = 1; i < n; i++) {
  20.  
  21.         t = borderArray[i - 1];
  22.  
  23.         while ((t > 0) && (substring[i] != substring[t]))
  24.             t = borderArray[t - 1];
  25.  
  26.         if (substring[i] == substring[t])
  27.             borderArray[i] = t + 1;
  28.         else
  29.             borderArray[i] = 0;
  30.     }
  31.  
  32.     for (int i = 0; i < source.size(); i++)
  33.     {
  34.         while (position == substring.size() || (position > 0 && substring[position] != source[i]))
  35.         {
  36.             position = borderArray[position - 1];
  37.             if (substring.size() - position > source.size() - i)
  38.                 break;
  39.         }
  40.  
  41.         if (source[i] == substring[position])
  42.             position++;
  43.  
  44.         if (position == substring.size())
  45.             res.push_back(i - position + 1);
  46.     }
  47.  
  48.     delete[] borderArray;
  49. }
  50.  
  51. //Не изменять метод main без крайней необходимости
  52. //ОБЯЗАТЕЛЬНО добавить в комментариях подробные пояснения и причины побудившие вас изменить код этого метода.
  53. int main()
  54. {
  55.     string t;
  56.     string p;
  57.     vector<int> res;
  58.  
  59.     ifstream fin;
  60.     fin.open("input.txt");
  61.     if (fin.is_open())
  62.     {
  63.         getline(fin, t);
  64.         getline(fin, p);
  65.         fin.close();
  66.     }
  67.  
  68.     getSubstrings(t, p, res);
  69.  
  70.     fstream fout;
  71.     fout.open("output.txt", ios::out);
  72.     fout << res.size() << "\n";
  73.     for (std::vector<int>::const_iterator i = res.begin(); i != res.end(); ++i)
  74.         fout << *i << "\n";
  75.     fout.close();
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement