forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNaivePatternSearch.java
More file actions
44 lines (37 loc) · 1.21 KB
/
NaivePatternSearch.java
File metadata and controls
44 lines (37 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.thealgorithms.strings;
import java.util.ArrayList;
import java.util.List;
public final class NaivePatternSearch {
// Private constructor to prevent instantiation
private NaivePatternSearch() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Naive pattern searching algorithm.
*
* @param text the text to be searched
* @param pattern the pattern to search for
* @return list of starting indices where pattern is found
* @throws IllegalArgumentException if text or pattern is null
*/
public static List<Integer> search(String text, String pattern) {
if (text == null || pattern == null) {
throw new IllegalArgumentException("Text and pattern must not be null");
}
List<Integer> result = new ArrayList<>();
int n = text.length();
int m = pattern.length();
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if (text.charAt(i + j) != pattern.charAt(j)) {
break;
}
}
if (j == m) {
result.add(i);
}
}
return result;
}
}