-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementedStrStr.java
More file actions
29 lines (24 loc) · 918 Bytes
/
ImplementedStrStr.java
File metadata and controls
29 lines (24 loc) · 918 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
public class ImplementedStrStr {
//With recursion:
public int strStr(String haystack, String needle) {
if (needle == null || needle == "") return 0;
if (haystack == null) return -1;
char[] cArr1 = haystack.toCharArray();
char[] cArr2 = needle.toCharArray();
for (int i = 0; i < cArr1.length; i++) {
if (subString(cArr1, cArr2, i, 0)) return i;
}
return -1;
}
private boolean subString(char[] cArr1, char[] cArr2, int start, int index) {
if (index == cArr2.length) {
return true;
}
if (start + index >= cArr1.length || cArr1[start + index] != cArr2[index]) return false;
return subString(cArr1, cArr2, start, index + 1);
}
public static void main(String[] args) {
ImplementedStrStr s = new ImplementedStrStr();
System.out.println(s.strStr("asd", "sd"));
}
}