Skip to content

Commit 8685c86

Browse files
authored
Updated : NaivePatternSearch.java
1 parent bbb645c commit 8685c86

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed
Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,44 @@
1-
package strings;
1+
package com.thealgorithms.strings;
22

33
import java.util.ArrayList;
44
import java.util.List;
55

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 {
6+
public final class NaivePatternSearch {
7+
8+
// Private constructor to prevent instantiation
9+
private NaivePatternSearch() {
10+
throw new UnsupportedOperationException("Utility class");
11+
}
1112

1213
/**
13-
* Finds all occurrences of a pattern in a given text using
14-
* the naive substring search algorithm.
14+
* Naive pattern searching algorithm.
1515
*
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.
16+
* @param text the text to be searched
17+
* @param pattern the pattern to search for
18+
* @return list of starting indices where pattern is found
19+
* @throws IllegalArgumentException if text or pattern is null
1920
*/
2021
public static List<Integer> search(String text, String pattern) {
22+
if (text == null || pattern == null) {
23+
throw new IllegalArgumentException("Text and pattern must not be null");
24+
}
25+
2126
List<Integer> result = new ArrayList<>();
2227
int n = text.length();
2328
int m = pattern.length();
2429

2530
for (int i = 0; i <= n - m; i++) {
26-
String sub = text.substring(i, i + m);
27-
if (sub.equals(pattern)) {
31+
int j;
32+
for (j = 0; j < m; j++) {
33+
if (text.charAt(i + j) != pattern.charAt(j)) {
34+
break;
35+
}
36+
}
37+
if (j == m) {
2838
result.add(i);
2939
}
3040
}
41+
3142
return result;
3243
}
3344
}

0 commit comments

Comments
 (0)