類別: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;
}