#28 Implement strStr()
题目地址:https://leetcode.com/problems/implement-strstr/
这道题easy估计是easy在了暴力搜索实现上。要达到O(n)的最优解需要KMP算法,而KMP算法我觉得难得不行。
初见(时间复杂度O(mn))
简单暴力的brute force:
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size() == 0) return 0;
else if(needle.size() > haystack.size()) return -1;
for(int indh = 0; indh < haystack.size() - needle.size() + 1; indh++){
for(int indn = 0; indn < needle.size(); indn++){
if(haystack.at(indh + indn) != needle.at(indn))
break;
else if(indn == needle.size() - 1)
return indh;
}
}
return -1;
}
};