Skip to content

Commit f0fe707

Browse files
committed
fix(naivestringsearch): was not working at all
1 parent 0d28a32 commit f0fe707

File tree

1 file changed

+30
-29
lines changed

1 file changed

+30
-29
lines changed

strings/naiveStringSearch.go

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,45 @@
11
/*
22
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,
44
it is added to positions.
55
66
Time Complexity : O(n*m)
77
n = length of text
8-
m = length of pattern
8+
m = length of pattern
99
*/
1010

1111
package main
1212

13-
import (
14-
"fmt"
13+
import (
14+
"fmt"
1515
)
1616

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
3233
}
3334

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+
}
4445
}

0 commit comments

Comments
 (0)