File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
src/main/java/com/thealgorithms/strings Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments