-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_28.java
37 lines (30 loc) · 862 Bytes
/
_28.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
package com.fishercoder.solutions;
public class _28 {
public static class Solution1 {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null || haystack.length() < needle.length()) {
return -1;
}
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
if (haystack.substring(i, i + needle.length()).equals(needle)) {
return i;
}
}
return -1;
}
}
public static class Solution2 {
public int strStr(String haystack, String needle) {
int n = needle.length();
int h = haystack.length();
for (int i = 0; i <= h - n; i++) {
for (int j = 0; j < n && haystack.charAt(i + j) == needle.charAt(j); j++) {
if (j == n - 1) {
return i;
}
}
}
return -1;
}
}
}