|
1 |
| -package strings; |
| 1 | +package com.thealgorithms.strings; |
2 | 2 |
|
3 | 3 | import java.util.ArrayList;
|
4 | 4 | import java.util.List;
|
5 | 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 { |
| 6 | +public final class NaivePatternSearch { |
| 7 | + |
| 8 | + // Private constructor to prevent instantiation |
| 9 | + private NaivePatternSearch() { |
| 10 | + throw new UnsupportedOperationException("Utility class"); |
| 11 | + } |
11 | 12 |
|
12 | 13 | /**
|
13 |
| - * Finds all occurrences of a pattern in a given text using |
14 |
| - * the naive substring search algorithm. |
| 14 | + * Naive pattern searching algorithm. |
15 | 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. |
| 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 |
19 | 20 | */
|
20 | 21 | 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 | + |
21 | 26 | List<Integer> result = new ArrayList<>();
|
22 | 27 | int n = text.length();
|
23 | 28 | int m = pattern.length();
|
24 | 29 |
|
25 | 30 | 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) { |
28 | 38 | result.add(i);
|
29 | 39 | }
|
30 | 40 | }
|
| 41 | + |
31 | 42 | return result;
|
32 | 43 | }
|
33 | 44 | }
|
0 commit comments