File tree Expand file tree Collapse file tree 2 files changed +47
-23
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +47
-23
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
- /**Implement strStr().
3
-
4
- Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
5
-
2
+ /**
3
+ * 28. Implement strStr()
4
+ *
5
+ * Implement strStr().
6
+ *
7
+ * Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
6
8
*/
7
9
public class _28 {
8
- /**You could use substring as follows, or use two pointers to go through the haystack, if substring API call is not allowed.*/
9
- public static int strStr (String haystack , String needle ) {
10
- if (haystack == null || needle == null || haystack .length () < needle .length ()) {
10
+
11
+ public static class Solution1 {
12
+ public int strStr (String haystack , String needle ) {
13
+ if (haystack == null || needle == null || haystack .length () < needle .length ()) {
11
14
return -1 ;
12
- }
15
+ }
13
16
14
- for (int i = 0 ; i <= haystack .length () - needle .length (); i ++) {
17
+ for (int i = 0 ; i <= haystack .length () - needle .length (); i ++) {
15
18
if (haystack .substring (i , i + needle .length ()).equals (needle )) {
16
- return i ;
19
+ return i ;
17
20
}
21
+ }
22
+ return -1 ;
18
23
}
19
- return -1 ;
20
- }
21
-
22
- public static void main (String ... args ) {
23
- // String haystack = "a";
24
- // String needle = "";
24
+ }
25
25
26
- // String haystack = "mississippi";
27
- // String needle = "a";
28
-
29
- String haystack = "a" ;
30
- String needle = "a" ;
31
- strStr (haystack , needle );
32
- }
33
26
}
Original file line number Diff line number Diff line change
1
+ package com .fishercoder ;
2
+
3
+ import com .fishercoder .solutions ._28 ;
4
+ import org .junit .Before ;
5
+ import org .junit .Test ;
6
+
7
+ import static junit .framework .TestCase .assertEquals ;
8
+
9
+ public class _28Test {
10
+ private static _28 .Solution1 solution1 ;
11
+
12
+ @ Before
13
+ public void setupForEachTest () {
14
+ solution1 = new _28 .Solution1 ();
15
+ }
16
+
17
+ @ Test
18
+ public void test1 () {
19
+ assertEquals (0 , solution1 .strStr ("a" , "" ));
20
+ }
21
+
22
+ @ Test
23
+ public void test2 () {
24
+ assertEquals (-1 , solution1 .strStr ("mississippi" , "a" ));
25
+ }
26
+
27
+ @ Test
28
+ public void test3 () {
29
+ assertEquals (0 , solution1 .strStr ("a" , "a" ));
30
+ }
31
+ }
You can’t perform that action at this time.
0 commit comments