Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
一句话就可以搞定的,不过我想出题的本意不在此吧。。。就遍历判断即可
public class Solution {
public int strStr(String haystack, String needle) {
if(haystack.length() < needle.length()) return -1;
int i=0, j=0;
for(; ; i++){
while(j<needle.length() && haystack.charAt(i+j)==needle.charAt(j)) j++;
if(j==needle.length()) break;
else j=0;
if(i==haystack.length()-needle.length()) break;
}
return j==needle.length() ? i : -1;
}
}
更简略的写法
public int strStr(String haystack, String needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) return i;
if (i + j == haystack.length()) return -1;
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}