1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Solution { public: int strStr(string s, string p) { int n = s.size(), m = p.size(); if(m == 0) return 0;
s.insert(s.begin(), ' '); p.insert(p.begin(), ' ');
vector<int> next(m + 1);
for(int i = 2, j = 0; i <= m; i++) { while(j && p[i] != p[j + 1]) j = next[j]; if(p[i] == p[j + 1]) j++; next[i] = j; }
for(int i = 1, j = 0; i <= n; i++) { while(j && s[i] != p[j + 1]) j = next[j]; if(s[i] == p[j + 1]) j++; if(j == m) return i - m; } return -1; }
int strStr(string s, string t) { int m = s.size(), n = t.size(); if (m < n) return -1; if (n == 0) return 0; int i = 0, j = 0, l = 0; while (i < m && j < n) { if(s[i] == t[j]) { i++; j++; } else { l++; i = l; j = 0; } } if (j == n) return l; return -1; } };
|