28. Implement strStr()
题目的原意是建立一个方法来可以找到一个String needle 在另外一个String haystack中第一次出现的index。
question: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路:最简单的可以考虑brute force的方式来逐字核对needle 和haystack中的单个字符是否一致,如果一直在核对下一个,直到needle 中最后一个字符。此时返回haystack的起始字符的index。
public int strStr(String haystack, String needle){
for (int i = 0; i < haystack.length()-needle.length()+1;i++){
int j = 0;
for (j = 0; j < needle.length() ; j++){
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
//loop to the end of target string
if (j == needle.length()) return i;
}
return -1;
}