BF算法:Brute Force (暴力算法)
时间复杂度:O(nm)
package main
import "fmt"
/**
* @Description: BF算法实现
* @param s1 主串
* @param s2 模式串
* @return int 匹配成功:返回模式串在主串的第一次出现的位置下标,否则返回-1
*/
func strBF(s1 string ,s2 string) int {
// 主串遍历
for i1 := range s1 {
matched := 1
// 模式串遍历
for i2, v2 := range s2 {
if fmt.Sprintf("%d",s1[i2+i1]) != fmt.Sprintf("%d",v2) {
matched = 0
break
}
}
if matched == 1 {
return i1
}
}
return -1
}
func main() {
s1 := "hello"
s2 := "lo"
ret := strBF(s1, s2)
fmt.Println(ret)
}