[leetcode]implement strstr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class  {

// return haystack.indexOf(needle);
// }

// public int strStr(String haystack, String needle){
// if(haystack == null || needle == null) return -1;
// //""和""返回0,但是""和"a"返回-1
// if(haystack.length() == 0) return needle.length() == 0 ? 0:-1;
// //暴力法
// for(int i = 0; i < haystack.length()-needle.length() + 1; i++){
// int j = 0;
// for(; j < needle.length(); j++){
// if(haystack.charAt(i+j) != needle.charAt(j)) break;
// }
// if(j == needle.length()) return i;
// }
// return -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;
}
}
}

}