- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathImplementStrStr28.java
More file actions
Latest commit
58 lines (51 loc) · 1.5 KB
/
Copy pathImplementStrStr28.java
File metadata and controls
58 lines (51 loc) · 1.5 KB
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
58
/**
* Implement strStr(). http://www.cplusplus.com/reference/cstring/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
*
*/
publicclassImplementStrStr28 {
publicintstrStr(Stringhaystack, Stringneedle) {
if (needle == null || needle.length() == 0) return0;
if (haystack == null || haystack.length() == 0 || haystack.length() < needle.length()) return -1;
inti = 0;
while (i <= haystack.length() - needle.length()) {
intj = 0;
intt = i;
while (j < needle.length() && haystack.charAt(t) == needle.charAt(j)) {
j++;
t++;
}
if (j == needle.length()) returni;
i++;
}
return -1;
}
/**
* https://leetcode.com/problems/implement-strstr/discuss/12811/Share-my-accepted-java-solution
*/
publicintstrStr2(Stringhaystack, Stringneedle) {
intl1 = haystack.length(), l2 = needle.length();
if (l1 < l2) {
return -1;
} elseif (l2 == 0) {
return0;
}
intthreshold = l1 - l2;
for (inti = 0; i <= threshold; ++i) {
if (haystack.substring(i,i+l2).equals(needle)) {
returni;
}
}
return -1;
}
}