Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add solution for problem 28 #179

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/main/java/com/fishercoder/solutions/_28.java
Original file line number Diff line number Diff line change
@@ -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;
}
}

}
5 changes: 5 additions & 0 deletions src/test/java/com/fishercoder/_28Test.java
Original file line number Diff line number Diff line change
@@ -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