Skip to content

Commit 4ac6264

Browse files
authored
Merge pull request #48 from Dharni0607/strings
created strings folder and added naiveStringSearch
2 parents 6c5febd + 074931f commit 4ac6264

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

strings/naiveStringSearch.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
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,
4+
it is added to positions.
5+
6+
Time Complexity : O(n*m)
7+
n = length of text
8+
m = length of pattern
9+
*/
10+
11+
package main
12+
13+
import (
14+
"fmt"
15+
)
16+
17+
func naivePatternSearch(text string, pattern string) []int {
18+
var positions []int
19+
for i := 0; i < len(text); 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+
if match {
28+
positions = append(positions, i)
29+
}
30+
}
31+
return positions
32+
}
33+
34+
func main() {
35+
text := "ABAAABCDBBABCDDEBCABC"
36+
pattern := "ABC"
37+
var positions []int
38+
positions = 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+
}
45+
}

0 commit comments

Comments
 (0)