File tree 2 files changed +74
-0
lines changed
2 files changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+
3
+ public class BruteForce {
4
+ public static void main (String [] args ) {
5
+ String text = "abcklmndefghklmnijklmnopqrsklmntuvwxyz" ;
6
+ String pattern = "klmno" ;
7
+ // time : O(M*N)
8
+ for (int i = 0 ; i < text .length (); i ++) {
9
+ int j ;
10
+ for (j = 0 ; j < pattern .length (); j ++) {
11
+ if (text .charAt (i + j ) != pattern .charAt (j ))
12
+ break ;
13
+ }
14
+
15
+ if (j == pattern .length ()) {
16
+ System .out .println ("Starting index : " + i );
17
+ return ;
18
+ }
19
+ }
20
+
21
+ System .out .println ("Not found" );
22
+ }
23
+ }
Original file line number Diff line number Diff line change
1
+ public class KnuthMorrisPratt {
2
+
3
+ public static int [] ComputeTempArray (String pattern ) {
4
+ int [] lps = new int [pattern .length ()];
5
+ int idx = 0 ;
6
+
7
+ for (int i = 1 ; i < pattern .length ();) {
8
+ if (pattern .charAt (i ) == pattern .charAt (idx )) {
9
+ lps [i ] = idx + 1 ;
10
+ idx ++;
11
+ i ++;
12
+ } else {
13
+ if (idx != 0 ) {
14
+ idx = lps [idx - 1 ];
15
+ } else {
16
+ lps [i ] = 0 ;
17
+ i ++;
18
+ }
19
+ }
20
+ }
21
+ return lps ;
22
+ }
23
+
24
+ public static void main (String [] args ) {
25
+ String text = "abcxabcdabcdabcaabcdabcyjjklqw" ;
26
+ String pattern = "abcdabcy" ;
27
+
28
+ int [] lps = ComputeTempArray (pattern );
29
+
30
+ int i = 0 , j = 0 ;
31
+ while (i < text .length () && j < pattern .length ()) {
32
+ if (text .charAt (i ) == pattern .charAt (j )) {
33
+ i ++;
34
+ j ++;
35
+ } else {
36
+ if (j != 0 ) {
37
+ j = lps [j - 1 ];
38
+ } else {
39
+ i ++;
40
+ }
41
+ }
42
+
43
+ if (j == pattern .length ()) {
44
+ System .out .println ("Starting index : " + (i - j ));
45
+ return ;
46
+ }
47
+ }
48
+
49
+ System .out .println ("Not found" );
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments