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
真的需要更多的考虑一下溢出问题,哎,不要想当然哦。看来我距离bug free的路太遥远
public class Solution {
public int strStr(String haystack, String needle) {
int k = needle.length();
if (k == 0)
return 0;
for(int i = 0; i < haystack.length() - k + 1; i++){
if (haystack.charAt(i) == needle.charAt(0)){
int j = 0;
for(j = 0; j < k; j++){
if (haystack.charAt(i+j) != needle.charAt(j))
break;
}
if(j == k)
return i;
}
}
return -1;
}
}