str.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package common
  2. import (
  3. "bytes"
  4. "fmt"
  5. goahocorasick "github.com/anknown/ahocorasick"
  6. "one-api/constant"
  7. "strings"
  8. )
  9. func SundaySearch(text string, pattern string) bool {
  10. // 计算偏移表
  11. offset := make(map[rune]int)
  12. for i, c := range pattern {
  13. offset[c] = len(pattern) - i
  14. }
  15. // 文本串长度和模式串长度
  16. n, m := len(text), len(pattern)
  17. // 主循环,i表示当前对齐的文本串位置
  18. for i := 0; i <= n-m; {
  19. // 检查子串
  20. j := 0
  21. for j < m && text[i+j] == pattern[j] {
  22. j++
  23. }
  24. // 如果完全匹配,返回匹配位置
  25. if j == m {
  26. return true
  27. }
  28. // 如果还有剩余字符,则检查下一位字符在偏移表中的值
  29. if i+m < n {
  30. next := rune(text[i+m])
  31. if val, ok := offset[next]; ok {
  32. i += val // 存在于偏移表中,进行跳跃
  33. } else {
  34. i += len(pattern) + 1 // 不存在于偏移表中,跳过整个模式串长度
  35. }
  36. } else {
  37. break
  38. }
  39. }
  40. return false // 如果没有找到匹配,返回-1
  41. }
  42. func RemoveDuplicate(s []string) []string {
  43. result := make([]string, 0, len(s))
  44. temp := map[string]struct{}{}
  45. for _, item := range s {
  46. if _, ok := temp[item]; !ok {
  47. temp[item] = struct{}{}
  48. result = append(result, item)
  49. }
  50. }
  51. return result
  52. }
  53. func InitAc() *goahocorasick.Machine {
  54. m := new(goahocorasick.Machine)
  55. dict := readRunes()
  56. if err := m.Build(dict); err != nil {
  57. fmt.Println(err)
  58. return nil
  59. }
  60. return m
  61. }
  62. func readRunes() [][]rune {
  63. var dict [][]rune
  64. for _, word := range constant.SensitiveWords {
  65. word = strings.ToLower(word)
  66. l := bytes.TrimSpace([]byte(word))
  67. dict = append(dict, bytes.Runes(l))
  68. }
  69. return dict
  70. }