KMP算法二
KMP算法二:
1 #include <string> 2 #include <vector> 3 #include <algorithm> 4 #include <iostream> 5 using namespace std; 6 7 class Solution 8 { 9 public: 10 void GetNext(string subStr, vector<int> &next) { 11 int i = 0; 12 int j = -1; 13 next[0] = -1; 14 int lengthOfSubStr = subStr.size(); 15 while (i < lengthOfSubStr - 1) { 16 if ((j == -1) || subStr[i] == subStr[j]) { 17 i++; 18 j++; 19 next[i] = j; 20 } else { 21 j = next[j]; 22 } 23 } 24 return; 25 } 26 void PrintNext(const vector<int> &next) { 27 for (const auto &val : next) { 28 cout << val << ' '; 29 } 30 cout << endl; 31 } 32 int Kmp(string mainStr, string subStr) { 33 int lengthOfMainStr = mainStr.size(); 34 int lenghtOfSubStr = subStr.size(); 35 if ((lengthOfMainStr == 0) || (lenghtOfSubStr == 0) || lengthOfMainStr < lenghtOfSubStr) { 36 return -1; 37 } 38 vector<int> next(lenghtOfSubStr); 39 GetNext(subStr, next); 40 int i = 0; 41 int j = 0; 42 while ((i < lengthOfMainStr) && (j < lenghtOfSubStr)) { 43 if ((j == -1) || mainStr[i] == subStr[j]) { 44 i++; 45 j++; 46 } else { 47 j = next[j]; 48 } 49 } 50 if (j == lenghtOfSubStr) { 51 return i - j; 52 } 53 return -1; 54 } 55 }; 56 57 int main() 58 { 59 Solution *test = new Solution(); 60 string text = "ABABABCABAABABABABA"; 61 string pattern = "ABABCABAA"; 62 vector<int> next(pattern.size()); 63 test->GetNext(pattern, next); 64 test->PrintNext(next); // -1, 0, 0, 1, 2, 0, 1, 2, 3 65 cout << test->Kmp(text, pattern) << endl; // 2 66 system("pause"); 67 return 0; 68 }
运行效果:

浙公网安备 33010602011771号