题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
思想:这题最开始想的是比较简单的线性算法,直接一个字符一个字符的对比,看来我还是比较蠢的。最牛逼的算法应该是比较典型的KMP算法,我记得当初在李老师的数据结构书上这个算法我搞了很久也没有彻底搞懂,暂时不考虑,这里介绍另一种算法:brute force的算法,假设原串的长度是n,匹配串的长度是m。思路很简单,就是对原串的每一个长度为m的字串都判断是否跟匹配串一致。总共有n-m+1个子串,所以算法时间复杂度为O((n-m+1)*m)=O(n*m),空间复杂度是O(1)。代码如下:
class Solution {
public:
int strStr(string haystack, string needle)
{
int lenSource = haystack.length(),lenNeed = needle.length();
if(lenNeed == 0) return 0;
for(int i =0,j=0 ; i<=lenSource - lenNeed;i++)
{
for(j= 0; j< lenNeed; j++)
if(haystack[i+j] != needle[j]) break;
if(j ==lenNeed) return i; //匹配成功
}
return -1;
}
};
KMP先马一个,这个元旦再聊!