Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
find needle in haystack 大海捞针。在长串中找短串。
思路是遍历长串,如果首字符等于短串首字符,就进入循环遍历短串看是否与长串该指针开始的短串相同。
public class Solution {
public int StrStr(string haystack, string needle) {
if (needle == "") return 0;
for(int i=0;i<haystack.Length;i++){
int j = 0;
while((i+j)<haystack.Length && haystack[i+j]==needle[j]){
if(j==needle.Length-1) return i;
j++;
}
if(i+j==haystack.Length) return -1;
}
return -1;
}
}