您的位置:首页 > 其它

leetcode 子串位置的寻找

2016-10-13 21:18 183 查看


28. Implement strStr()

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
这个是求子串的位置,仔细想想并没有那么简单,说说这段代码的思路
如果字符为空指针,返回-1;
如果寻找的字符为空,那么返回0
使用while来遍历,如果一直相等就一直执行,直到最后,如果中间有不相等的,那么就从上一个位置的后一个位置开始(这里可以使用kmp来做,个人不是很熟悉),然后最后根据是否到达了寻找串的尾部来判断是否寻找成功
代码:
int strStr(char* haystack, char* needle) {
if(!haystack||!needle) return -1;
else if(*needle=='\0') return 0;
int result=-1;
int i=0,j=0;
while(needle[i]!='\0'&&haystack[j]!='\0'){
if(needle[i]==haystack[j]){
if(result==-1) result=j;
i++;j++;
}else{
j=(result==-1)?j+1:result+1;
i=0;
result=-1;
}
}
return (needle[i]!='\0')?-1:result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode