File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments