forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_28.java
33 lines (27 loc) · 972 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
package com.fishercoder.solutions;
/**Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*/
public class _28 {
/**You could use substring as follows, or use two pointers to go through the haystack, if substring API call is not allowed.*/
public static 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 void main(String... args) {
// String haystack = "a";
// String needle = "";
// String haystack = "mississippi";
// String needle = "a";
String haystack = "a";
String needle = "a";
strStr(haystack, needle);
}
}