-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrStr.java
More file actions
42 lines (34 loc) · 1.13 KB
/
Copy pathStrStr.java
File metadata and controls
42 lines (34 loc) · 1.13 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
package strStr;
public class StrStr {
public int strStr(String haystack, String needle) {
if (needle.length() == 0)
return 0;
else if (haystack.length() == 0 || haystack.length() < needle.length())
return -1;
else {
for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
boolean occur = true;
for (int j = 0; j < needle.length(); j++) {
char char_haystack = haystack.charAt(i+j);
char char_needle = needle.charAt(j);
if (char_haystack != char_needle) {
occur = false;
}
if (!occur) {
break;
}
}
if (occur) {
return i;
}
}
return -1;
}
}
public static void main(String[] args) {
String haystack = "abcd";
String needle = "cde";
StrStr solution = new StrStr();
System.out.println("result: " + solution.strStr(haystack, needle));
}
}