028实现strStr()

时间:2022-04-26 16:02:22
 #pragma once
#include "000库函数.h" /*********************自解**************/
//使用算法中的find 12ms
class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack.size() == && needle.size() != )return -;
if (needle.size() == )return ;
return haystack.find(needle);
}
}; /********************博客解法*****************/
//使用暴力遍寻法 44ms
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) return ;
int m = haystack.size(), n = needle.size();
if (m < n) return -;
for (int i = ; i <= m - n; ++i) {
int j = ;
for (j = ; j < n; ++j) {
if (haystack[i + j] != needle[j]) break;
}
if (j == n) return i;
}
return -;
}
}; void T028() {
string haystack, needle;
haystack = "hello";
needle = "ll";
Solution s;
cout << s.strStr(haystack, needle) << endl;
haystack = "aaaaa";
needle = "bba";
cout << s.strStr(haystack, needle) << endl;
}