Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
应该用KMP,但是没用KMP好像也过去了。。。。。
int strStr(char * haystack, char * needle){
int i = 0,j =0,t=i;//一定要有t
while (haystack[i]&&needle[j]){
if (haystack[i] == needle[j]){
i++;
j++;
continue;
//C 语言中的 continue 语句有点像 break 语句。但它不是强制终止,continue 会跳过当前循环中的代码,强迫开始下一次循环。
} else{
t=t+1;
i=t;
j=0;
}
}
//如果needle串到了结尾的时候,代表顺利找到
if (needle[j] == '\0'){
return t;
}
//否则返回-1,没找到
return -1;
}