问题描述
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
分析
1.strStr()是C++的函数,和Java的indexOf()和substring()作用差不多,所以不能用这两个现成的函数。
2.需要两个指针分别指向haystack和needle,双重for循环,遍历haystack与needle进行比较,只要与needle的第一个字符不同就跳出本层循环,进行haystack下个字符的比较,直到needle的所有字符都满足条件。
代码如下:
public int strStr(String haystack, String needle) {
if(haystack == "") return -1;
for(int i=0; ; i++){
for(int j=0;;j++){
if(j == needle.length()) return i; //说明needle存在于haystack中
if(i+j == haystack.length()) return -1; //haystack已经遍历完
if(needle.charAt(j) != haystack.charAt(i+j)) break;
}
}
}
网友评论