Skip to content

Commit a3083ec

Browse files
authored
feat: add Naive Pattern Search algorithm
This commit adds the Naive Pattern Search algorithm implementation in Java. The algorithm scans the text from left to right and checks each substring of length m (pattern length) to find matches. - New class: NaivePatternSearch.java - Provides `search(String text, String pattern)` method returning all match indices - Includes a sample main() for demonstration Time Complexity: O(n * m) Space Complexity: O(1)
1 parent e78d53d commit a3083ec

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package strings;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* Naive Pattern Searching algorithm.
8+
* Reference: https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search
9+
*/
10+
public class NaivePatternSearch {
11+
12+
/**
13+
* Finds all occurrences of a pattern in a given text using
14+
* the naive substring search algorithm.
15+
*
16+
* @param text The text in which to search.
17+
* @param pattern The pattern to search for.
18+
* @return List of starting indices where the pattern is found.
19+
*/
20+
public static List<Integer> search(String text, String pattern) {
21+
List<Integer> result = new ArrayList<>();
22+
int n = text.length();
23+
int m = pattern.length();
24+
25+
for (int i = 0; i <= n - m; i++) {
26+
String sub = text.substring(i, i + m);
27+
if (sub.equals(pattern)) {
28+
result.add(i);
29+
}
30+
}
31+
return result;
32+
}
33+
}

0 commit comments

Comments
 (0)