|
1 | 1 | /*
|
2 | 2 | This algorithm tries to search the given pattern in the given text.
|
3 |
| -If pattern is found from index position i in the text, |
| 3 | +If pattern is found from index position i in the text, |
4 | 4 | it is added to positions.
|
5 | 5 |
|
6 | 6 | Time Complexity : O(n*m)
|
7 | 7 | n = length of text
|
8 |
| - m = length of pattern |
| 8 | + m = length of pattern |
9 | 9 | */
|
10 | 10 |
|
11 | 11 | package main
|
12 | 12 |
|
13 |
| -import ( |
14 |
| - "fmt" |
| 13 | +import ( |
| 14 | + "fmt" |
15 | 15 | )
|
16 | 16 |
|
17 |
| -func naivePatternSearch(text string, pattern string) []int { |
18 |
| - var positions []int |
19 |
| - for i := 0; i < len(text)-len(pattern); i++ { |
20 |
| - var match bool = true |
21 |
| - j := i +(len(pattern)) |
22 |
| - if text[i+j] != pattern[j] { |
23 |
| - match = false |
24 |
| - break |
25 |
| - } |
26 |
| - |
27 |
| - if match { |
28 |
| - positions = append(positions, i) |
29 |
| - } |
30 |
| - } |
31 |
| - return positions |
| 17 | +func naivePatternSearch(text string, pattern string) []int { |
| 18 | + var positions []int |
| 19 | + for i := 0; i < len(text)-len(pattern); i++ { |
| 20 | + var match bool = true |
| 21 | + for j := 0; j < len(pattern); j++ { |
| 22 | + if text[i+j] != pattern[j] { |
| 23 | + match = false |
| 24 | + break |
| 25 | + } |
| 26 | + |
| 27 | + } |
| 28 | + if match { |
| 29 | + positions = append(positions, i) |
| 30 | + } |
| 31 | + } |
| 32 | + return positions |
32 | 33 | }
|
33 | 34 |
|
34 |
| -func main() { |
35 |
| - text := "ABAAABCDBBABCDDEBCABC" |
36 |
| - pattern := "ABC" |
37 |
| - var positions []int = naivePatternSearch(text, pattern) |
38 |
| - if len(positions) == 0 { |
39 |
| - fmt.Printf("Pattern not found in given text!") |
40 |
| - } else { |
41 |
| - fmt.Printf("Pattern found in following position:\n") |
42 |
| - fmt.Printf("%v", positions) |
43 |
| - } |
| 35 | +func main() { |
| 36 | + text := "ABAAABCDBBABCDDEBCABC" |
| 37 | + pattern := "ABC" |
| 38 | + var positions []int = naivePatternSearch(text, pattern) |
| 39 | + if len(positions) == 0 { |
| 40 | + fmt.Printf("Pattern not found in given text!") |
| 41 | + } else { |
| 42 | + fmt.Printf("Pattern found in following position:\n") |
| 43 | + fmt.Printf("%v", positions) |
| 44 | + } |
44 | 45 | }
|
0 commit comments