Skip to content
Closed
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
33 changes: 33 additions & 0 deletions src/main/java/com/thealgorithms/strings/NaivePatternSearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package strings;

import java.util.ArrayList;
import java.util.List;

/**
* Naive Pattern Searching algorithm.
* Reference: https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search
*/
public class NaivePatternSearch {

/**
* Finds all occurrences of a pattern in a given text using
* the naive substring search algorithm.
*
* @param text The text in which to search.
* @param pattern The pattern to search for.
* @return List of starting indices where the pattern is found.
*/
public static List<Integer> search(String text, String pattern) {
List<Integer> result = new ArrayList<>();
int n = text.length();
int m = pattern.length();

for (int i = 0; i <= n - m; i++) {
String sub = text.substring(i, i + m);
if (sub.equals(pattern)) {
result.add(i);
}
}
return result;
}
}
Loading