diff --git a/src/main/java/com/fishercoder/solutions/_28.java b/src/main/java/com/fishercoder/solutions/_28.java index 582899b0dc..8e0323ad32 100644 --- a/src/main/java/com/fishercoder/solutions/_28.java +++ b/src/main/java/com/fishercoder/solutions/_28.java @@ -17,4 +17,21 @@ public int strStr(String haystack, String needle) { } } + public static class Solution2 { + public int strStr(String haystack, String needle) { + + int n = needle.length(); + int h = haystack.length(); + + for (int i = 0; i <= h - n; i++) { + for (int j = 0; j < n && haystack.charAt(i + j) == needle.charAt(j); j++) { + if (j == n - 1) { + return i; + } + } + } + return -1; + } + } + } diff --git a/src/test/java/com/fishercoder/_28Test.java b/src/test/java/com/fishercoder/_28Test.java index ce9378a6f2..22f42d6886 100644 --- a/src/test/java/com/fishercoder/_28Test.java +++ b/src/test/java/com/fishercoder/_28Test.java @@ -8,20 +8,25 @@ public class _28Test { private static _28.Solution1 solution1; + private static _28.Solution2 solution2; @Before public void setupForEachTest() { solution1 = new _28.Solution1(); + solution2 = new _28.Solution2(); } @Test public void test1() { assertEquals(0, solution1.strStr("a", "")); + assertEquals(0, solution2.strStr("sadbutsad", "sad")); } @Test public void test2() { + assertEquals(-1, solution1.strStr("mississippi", "a")); + assertEquals(8, solution2.strStr("leetcodea", "a")); } @Test