028.Implement strStr()

Solution 1: accepted 18ms

Brute force.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
if (needle.length() == 0) {
return 0;
}
int j = 0;
for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
for (j = 0; j < needle.length(); j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
if (j == needle.length()) {
return i;
}
}
return -1;
}

Solution 2: accepted 58%

KMP.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
public int strStr(String haystack, String needle) {
int hayLen = haystack.length();
int nedLen = needle.length();
if (nedLen == 0) {
return 0;
}
for(int i = 0; i < hayLen - nedLen + 1; i++) {
int hay = i;
int ned = 0;
while (haystack.charAt(hay) == needle.charAt(ned)) {
hay++;
ned++;
if (ned == nedLen)
return i;
continue;
}
}
return -1;
}
}

Neat but slower (28%) KMP.

1
2
3
4
5
6
7
8
9
10
11
public class Solution {
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 (haystack.charAt(i + j) != needle.charAt(j)) break;
}
}
}
}