简单的字符串匹配
方法一、暴力匹配
needle 与 haystack 的所有长度为 m 的字符串均匹配一次。每次匹配失败就立刻停止当前的匹配,继续对下一个字符串匹配,当前字符串匹配成功,返回当前开始位置,所有均失败返回 -1 ;
int strStr(char* haystack, char* needle) {int n = strlen(haystack), m = strlen(needle);for (int i = 0; i + m <= n; i++) {bool flag = true;for (int j = 0; j < m; j++) {if (haystack[i + j] != needle[j]) {flag = false;break;}}if (flag) {return i;}}return -1;}
class Solution {public:int strStr(string haystack, string needle) {int n = haystack.size(), m = needle.size();for (int i = 0; i + m <= n; i++) {bool flag = true;for (int j = 0; j < m; j++) {if (haystack[i + j] != needle[j]) {flag = false;break;}}if(flag) {return i;}}return i;}}
时间复杂度:O(n x m);
空间复杂度:O(1);
Knuth-Morris-Pratt 算法
KMP 算法
思想:(待补充)
int strStr(char* haystack, char* needle) {int n = strlen(haystack), m = strlen(needle);if (m == 0) {return 0;}int pi[m];pi[0] = 0;for (int i = 1, j = 0; i < m; i++) {while (j > 0 && needle[i] != neeldle[j]) {j = pi[j - 1];}if (needle[i] == needle[j]) {j++;}pi[i] = j;}for (int i = 0, j = 0; i < n; i++) {while (j > 0 && haystack[i] != needle[j]) {j = pi[j - 1];}if (haystack[i] == needle[j]) {j++;}if (j == m) {return i - m + 1;}}return -1;}
class Solution {public:int strStr(string haystack, string needle) {int n = haystack.size(), m = needle.size();if (mm == 0) {return 0;}vector<int> pi[m];for (int i = 1, j = 0; i < m; i++) {while (j > 0 && needle[i] != needle[j]) {j = pi[j - 1];}if (needle[i] == needle[j]) {j++;}pi[i] = j;}for (int i = 0, j = 0; i < n; i++) {while (j > 0 && haystack[i] != needle[j]) {j = pi[j - 1];}if (haystack[i] == needle[j]) {j++;}if (j == m) {return i - m + 1;}}return -1;}}
复杂度
- 时间复杂度:O(n + m)
- 空间复杂度:O(m)
