Skip to content

Commit 95dbb95

Browse files
EASY/src/easy/ImplementStrStr.java
1 parent 34e6d77 commit 95dbb95

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

EASY/src/easy/ImplementStrStr.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package easy;
2+
3+
public class ImplementStrStr {
4+
/**You could use substring as follows, or use two pointers to go through the haystack, if substring API call is not allowed.*/
5+
public static int strStr(String haystack, String needle) {
6+
if(haystack == null || needle == null){
7+
return -1;
8+
}
9+
if(haystack.isEmpty()){
10+
return needle.isEmpty() ? 0 : -1;
11+
}
12+
if(needle.isEmpty()){
13+
return 0;
14+
}
15+
for(int i = 0; i < haystack.length() - needle.length()+1; i++){
16+
if(haystack.substring(i, i+needle.length()).equals(needle)) return i;
17+
}
18+
return -1;
19+
}
20+
21+
public static void main(String...args){
22+
// String haystack = "a";
23+
// String needle = "";
24+
25+
// String haystack = "mississippi";
26+
// String needle = "a";
27+
28+
String haystack = "a";
29+
String needle = "a";
30+
strStr(haystack, needle);
31+
}
32+
}

0 commit comments

Comments
 (0)