28-Implement strStr()(匹配字符串问题KMP算法)

类别:string

题目描述

这里写图片描述

算法

使用暴力求解的算法效率低,出现runtime error,时间复杂度是O(nm)
可以使用string的find函数,但是具体的实现应该参考KMP算法:时间按复杂度是O(n+m):
https://www.61mon.com/index.php/archives/183/(里面有详细的KMP算法介绍和代码实现,此处不做赘述)

代码实现

#include <iostream>
#include <string>
using namespace std;


int strStr(string haystack, string needle) {
    // runtime error
    // int k = 0, i = 0, n = 0;
    // bool flag = false;
    // for (i = 0; i < haystack.length(); ++i) {
    //  n = 0;
    //  if (haystack[i] == needle[0]) {
    //      k = i;
    //      for (int j = 0; j < needle.length(); ++j) {
    //          if (haystack[k++] == needle[j]) {
    //              n++;
    //          }
    //      }
    //      if (n == needle.length()) {
    //          flag = true;
    //          break;
    //      }
    //  }
    // }
    // if (flag == true) return i;
    // else return -1;
    /*********************ACCEPTED*************************/
    int found = haystack.find(needle);
    if (found != std::string::npos) return found;
    else return -1;
    /*************************KMP**************************/

}

int main() {
    string haystack = "", needle = "";
    cin >> haystack;
    cin >> needle;
    cout << strStr(haystack, needle) << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章