KMP算法
| 下标 | 0 | 1 | 2 | 3 | 4 |
| a | b | a | b | c | |
| next | -1 | 0 | 0 | 1 | 2 |
求解next数组时,下标为0,1已知,从下标为2开始
1 //KMP算法 2 class Solution 3 { 4 public: 5 //求next数组 6 vector<int> pre(string& str2) 7 { 8 if(str2.size() == 1) return {-1};//如果模式串大小为1,直接返回-1 9 vector<int> next(str2.size());//next数组的大小与模式串相同 10 next[0] = -1; 11 next[1] = 0; 12 int i = 2; //从下标为2开始 13 int cn = 0;//cn属于可以跳到的位置 14 while(i < str2.size()) 15 { //如果前一个字符与跳到的位置对应的字符相等 16 if(str2[i - 1] == str2[cn]) next[i++] = ++cn; 17 else 18 { 19 if(cn > 0) cn = next[cn]; //如果还可以跳 20 else next[i++] = 0; 21 } 22 } 23 return next; 24 } 25 26 //str1长串、str2模式串 27 int strStr(string str1, string str2) 28 { 29 if(str1.size() < str2.size()) return -1;//如果长串小于模式串,直接返回-1 30 if(str2.empty()) return 0; //任何一个空模式串都可以与长串匹配,返回下标0 31 int i1 = 0; 32 int i2 = 0; 33 vector<int> next = pre(str2); 34 35 while(i1 < str1.size() && i2 < str2.size()) 36 { 37 if(str1[i1] == str2[i2])//如果相等,都++ 38 { 39 i1++,i2++; 40 } 41 else if(next[i2] == -1) i1++; //如果不等且next数组为-1,说明模式串不可以动了,就让长串向右移一个位置 42 else i2 = next[i2];//如果不等且next数组不为-1,模式串跳到next数组的位置 43 } 44 return i2 == str2.size() ? i1 - i2 : -1;//如果跳到了末尾,就返回相应的下标。反之,返回-1 45 } 46 };
2020-03-15
17:25:29
Mamba never out

浙公网安备 33010602011771号