Skip to content

Commit 421e719

Browse files
committed
feat: shrink repeated patterns
1 parent d8be1c9 commit 421e719

2 files changed

Lines changed: 38 additions & 5 deletions

File tree

chat/init.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,16 @@ func AskCustom[T any](grp int64, f func(int, string) T) []T {
4747
}
4848

4949
func Sanitize(msg string) string {
50-
_, s, ok := strings.Cut(msg, "】")
51-
if ok {
52-
return s
50+
i := strings.LastIndex(msg, "】")
51+
if i > 0 {
52+
msg = msg[i:]
53+
} else {
54+
i = strings.LastIndex(msg, "]")
55+
if i > 0 {
56+
msg = msg[i:]
57+
}
5358
}
54-
_, s, ok = strings.Cut(msg, "]")
55-
if ok {
59+
if s, n := findRepeatedPattern(msg, 10); n > 0 {
5660
return s
5761
}
5862
return msg

chat/str.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package chat
2+
3+
// findRepeatedPattern 查找字符串中连续重复次数超过 n 的子串
4+
func findRepeatedPattern(s string, n int) (string, int) {
5+
runes := []rune(s) // 将字符串转换为 rune 切片,支持 Unicode 字符
6+
length := len(runes)
7+
8+
// 遍历所有可能的子串长度,从 1 到字符串长度的一半
9+
for size := 1; size <= length/2; size++ {
10+
// 遍历字符串的每个起始位置
11+
for i := 0; i <= length-size*n; i++ {
12+
pattern := runes[i : i+size] // 当前子串模式
13+
count := 1 // 初始化重复次数
14+
15+
// 检查后续是否连续出现相同的子串
16+
for j := i + size; j+size <= length; j += size {
17+
if string(runes[j:j+size]) == string(pattern) {
18+
count++
19+
if count >= n {
20+
return string(pattern), count
21+
}
22+
} else {
23+
break
24+
}
25+
}
26+
}
27+
}
28+
return "", 0 // 未找到满足条件的重复子串
29+
}

0 commit comments

Comments
 (0)