Implement strStr() LeetCode solution in Java

1
class Solution {
2
public int strStr(String haystack, String needle) {
3

4
if (needle.length() > haystack.length()) {
5
return -1;
6
}
7
if (needle.length() == haystack.length()) {
8
if (haystack.equals(needle)) {
9
return 0;
10
}
11
return -1;
12
}
13

14
int i = 0;
15
int j = 0;
16
while (i < needle.length() && j < haystack.length()) {
17
if (needle.charAt(i) == haystack.charAt(j)) {
18
i++;
19
j++;
20
if (i == needle.length()) {
21
return j - needle.length();
22
}
23
} else {
24
j = j - i + 1; // backtrack to last pos+1 where there was a probable match
25
i = 0;
26
}
27
}
28

29
return -1;
30
}
31
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0