Skip to content

Add solution for problem 28 #179

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: add solution to problem 28
  • Loading branch information
ashmichheda committed Nov 12, 2023
commit 57ed447cb0a468876653fffbaf9e26f04ab5b006
16 changes: 16 additions & 0 deletions src/main/java/com/fishercoder/solutions/_28.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,20 @@ 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
Expand Up @@ -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
Expand Down