-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImplementStrStr.java
More file actions
31 lines (23 loc) · 877 Bytes
/
Copy pathImplementStrStr.java
File metadata and controls
31 lines (23 loc) · 877 Bytes
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
// Implement strStr().
// Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
package leetcode.string;
public class ImplementStrStr {
public int strStr(String haystack, String needle) {
if (needle.isEmpty())
return 0;
for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
for (int j = 0; j < needle.length(); j++) {
if (haystack.charAt(i + j) != needle.charAt(j))
break;
if (j == needle.length() - 1)
return i;
}
}
return -1;
}
public static void main(String[] args) {
ImplementStrStr sln = new ImplementStrStr();
System.out.println(sln.strStr("heello", "ll"));
System.out.println(sln.strStr("mississippi", "issip"));
}
}