forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0028-find-the-index-of-the-first-occurrence-in-a-string.java
57 lines (54 loc) · 1.53 KB
/
0028-find-the-index-of-the-first-occurrence-in-a-string.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Solution One
public class Solution {
public int strStr(String haystack, String needle) {
if (needle.isEmpty()) {
return 0;
}
int[] lps = new int[needle.length()];
int prevLPS = 0, i = 1;
while (i < needle.length()) {
if (needle.charAt(i) == needle.charAt(prevLPS)) {
lps[i] = ++prevLPS;
i++;
} else {
if (prevLPS == 0) {
lps[i] = 0;
i++;
} else {
prevLPS = lps[prevLPS - 1];
}
}
}
int j = 0; // ptr for needle
for (i = 0; i < haystack.length(); ) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
} else {
if (j == 0) {
i++;
} else {
j = lps[j - 1];
}
}
if (j == needle.length()) {
return i - j;
}
}
return -1;
}
}
// Solution Two (Linear search using indexOf method for arrays)
class Solution {
public int strStr(String haystack, String needle) {
int result = 0;
if (haystack.length() <= 0 && needle.length() > 0) return -1;
if (haystack.length() != 0) {
int occurence = haystack.indexOf(needle);
if (occurence == -1)
return occurence;
result = occurence;
}
return result;
}
}