#28 Implement strStr()
題目地址:https://leetcode.com/problems/implement-strstr/
這道題easy估計是easy在了暴力搜索實現(xiàn)上。要達(dá)到O(n)的最優(yōu)解需要KMP算法,而KMP算法我覺得難得不行。
初見(時間復(fù)雜度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;
}
};