题目:
这题考察 KMP 的
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
| 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 and 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 and s[i] != p[j + 1]) j = next[j]; if(s[i] == p[j + 1]) j++; if(j == m) return i - m; } return -1; } };
|
可以直接用 C++的 string.find 函数
1 2 3 4 5 6 7 8
| #include <string> using std::string;
class Solution { public: int strStr(string haystack, string needle) { return haystack.find(needle); } };
|