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
class Solution {
public int strStr(String haystack, String needle) {
int f=-1,j=0;
char a[] = haystack.toCharArray();
char b[] = needle.toCharArray();
if(b.length==0)//needle为空
return 0;
if(a.length<b.length)//haystack长于needle
return -1;
int t=0;
for(int i=0;i<a.length-b.length+1;i++){
if(a[i]==b[j]){//匹配上了第一个字符
while(j<=b.length-1){ //逐个比较needle的后续字符串
t++;//记位符
if(t==b.length){
f=i;
return f;
}
if(a[i+t]!=b[++j]){//后续有不连续相等的字符,从a下一个位置开始比较,其余参数重置
f=-1;
t=0;
j=0;
break;
}
}
}
}
return f;
}
}