题目
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路
按照下标递增的顺序比较haystack中的所有子字符串和needle。
代码
public class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals(""))
return 0;
int len1 = haystack.length();
int len2 = needle.length();
for(int beginIndex = 0; beginIndex <= len1 - len2; beginIndex++) {
int i = beginIndex;
int j = 0;
while(j != len2 && haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
}
if(j == len2)
return beginIndex;
}
return -1;
}
}