Skip to content

Commit dc189f0

Browse files
committed
Add NaiveStringMatching activity
1 parent 9fdbaaf commit dc189f0

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.packt.datastructuresandalg.lesson5.activity.naivestringmatching;
2+
3+
import java.util.List;
4+
5+
public class NaiveStringMatching {
6+
public List<Integer> match(String P, String T) { return null; }
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.packt.datastructuresandalg.lesson5.activity.naivestringmatching.solution;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class NaiveStringMatching {
7+
public List<Integer> match(String P, String T) {
8+
int n = T.length();
9+
int m = P.length();
10+
List<Integer> shifts = new ArrayList<>();
11+
for (int i = 0; i < n - m + 1; i++) {
12+
boolean hasMatch = true;
13+
for (int j = 0; j < m; j++) {
14+
if (P.charAt(j) != T.charAt(i + j)) {
15+
hasMatch = false;
16+
break;
17+
}
18+
}
19+
if (hasMatch)
20+
shifts.add(i);
21+
}
22+
return shifts;
23+
}
24+
25+
public static void main(String[] args) {
26+
NaiveStringMatching nsm = new NaiveStringMatching();
27+
List<Integer> matches = nsm.match("aab", "acaabc");
28+
for (Integer i : matches)
29+
System.out.println(i);
30+
}
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.packt.datastructuresandalg.lesson5.activity.naivestringmatching;
2+
3+
import junit.framework.TestCase;
4+
5+
import java.util.ArrayList;
6+
import java.util.Arrays;
7+
8+
public class NaiveStringMatchingTest extends TestCase {
9+
NaiveStringMatching nsm = new NaiveStringMatching();
10+
11+
public void test1() {
12+
assertTrue(nsm.match("abc", "abc").equals(Arrays.asList(0)));
13+
}
14+
15+
public void test2() {
16+
assertTrue(nsm.match("abd", "abc").equals(new ArrayList<>()));
17+
}
18+
19+
public void test3() {
20+
assertTrue(nsm.match("abcde", "abc").equals(new ArrayList<>()));
21+
}
22+
23+
public void test4() {
24+
assertTrue(nsm.match("aab", "acaabc").equals(Arrays.asList(2)));
25+
}
26+
27+
public void test5() {
28+
assertTrue(nsm.match("aab", "acaabcaab").equals(Arrays.asList(2, 6)));
29+
}
30+
}

0 commit comments

Comments
 (0)