Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
Java:
public class Solution {
public int strStr(String haystack, String needle) {
if(haystack == null || needle == null) return 0;
int haylength = haystack.length();
int needlength = needle.length();
if(needlength == 0) return 0;
if(haylength < needlength) return -1;
for(int i=0; i<haylength; i++)
{
if(i+needlength > haylength)
return -1;
for(int j=0; j<needlength; j++)
{
if(needle.charAt(j) != haystack.charAt(i+j)) break;
if(needle.charAt(j) == haystack.charAt(i+j) && j == needlength -1)
return i;
}
}
return -1;
}
}