您的位置:首页 > 其它

Implement strStr()

2015-10-12 23:05 211 查看

题目:Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

思路:从后向前

最难得方法是使用KMP算法,不过程序是easy级别的,应该是可以使用从前往后的算法的。效率为n的平方。

代码:

class Solution {
public:
int strStr(string haystack, string needle) {

if(needle.length()<1){
return 0;
}

int length1=haystack.length();
int length2=needle.length();
int i,j;
for(i=0;i<=length1-length2;i++){
if(haystack[i]==needle[0]){
for(j=0;j<length2;j++){
if(haystack[i+j]!=needle[j]){
break;
}
}
if(j==length2){

return i;
}
}
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: