-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrStr.java
More file actions
45 lines (41 loc) · 1.01 KB
/
StrStr.java
File metadata and controls
45 lines (41 loc) · 1.01 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
43
44
45
package codingInterview;
public class StrStr {
public static void main(String[] args) {
// TODO Auto-generated method stub
String hayStack = "hakdhgkgoodadlkg";
String needle = null;
String subString = findStr(hayStack, needle);
System.out.println(subString == null ? "not found"
: "found, subString : " + subString);
}
private static String findStr(String hayStack, String needle) {
// TODO Auto-generated method stub
if (hayStack == null || needle == null) {
return null;
}
int hayStackLen = hayStack.length();
int needleLen = needle.length();
if (hayStackLen == needleLen && needleLen == 0) {
return "";
}
if (needleLen == 0) {
return hayStack;
}
for (int i = 0; i < hayStackLen; i++) {
if (hayStackLen - i + 1 < needleLen) {
return null;
}
int k = i;
int j = 0;
while (j < needleLen && k < hayStackLen
&& hayStack.charAt(k) == needle.charAt(j)) {
j++;
k++;
if (j >= needleLen) {
return hayStack.substring(i);
}
}
}
return null;
}
}