-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathImplementStrStr.java
38 lines (30 loc) · 931 Bytes
/
ImplementStrStr.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
package problems.leetcode;
/**
* https://leetcode.com/problems/implement-strstr/
*/
public class ImplementStrStr {
public static void main(String[] args) {
String haystack = "hello";
String needle = "lok";
System.out.println(strStr(haystack, needle));
}
public static int strStr(String haystack, String needle) {
if (haystack == null || needle == null || haystack.length() < needle.length()) {
return -1;
} else if (needle.length() == 0) {
return 0;
}
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
int j = 0;
for (; j < needle.length(); j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
if (j == needle.length()) {
return i;
}
}
return -1;
}
}