@@ -10,46 +10,49 @@ type entry struct {
10
10
source , target string
11
11
}
12
12
13
- func findReplaceString (S string , indexes []int , sources []string , targets []string ) string {
14
- entries := make ([]* entry , len (indexes ))
15
- for i := range entries {
16
- entries [i ] = & entry {
13
+ func findReplaceString (Str string , indexes []int , sources []string , targets []string ) string {
14
+ es := make ([]* entry , len (indexes ))
15
+ for i := range es {
16
+ es [i ] = & entry {
17
17
idx : indexes [i ],
18
18
source : sources [i ],
19
19
target : targets [i ],
20
20
}
21
21
}
22
22
23
- sort .Slice (entries , func (i int , j int ) bool {
24
- return entries [i ].idx < entries [j ].idx
23
+ // 按照 idx 升排序
24
+ sort .Slice (es , func (i int , j int ) bool {
25
+ return es [i ].idx < es [j ].idx
25
26
})
26
27
27
- size := len (S )
28
-
29
- ss := make ([]string , 0 , len (indexes )* 2 + 2 )
28
+ size := len (Str )
29
+ ss := make ([]string , 0 , len (indexes )* 2 + 1 )
30
30
31
31
end := 0
32
- for i := range entries {
32
+ // 按照 es 分割 Str
33
+ for _ , e := range es {
33
34
begin := end
34
- ss = append (ss , S [begin :entries [ i ] .idx ])
35
- end = min (size , entries [ i ] .idx + len (entries [ i ] .source ))
36
- ss = append (ss , S [ entries [ i ] .idx :end ])
35
+ ss = append (ss , Str [begin :e .idx ])
36
+ end = min (size , e .idx + len (e .source ))
37
+ ss = append (ss , Str [ e .idx :end ])
37
38
}
38
-
39
+ // 尾部有剩余,也要加入 ss
39
40
if end < size {
40
- ss = append (ss , S [end :])
41
+ ss = append (ss , Str [end :])
41
42
}
42
43
43
44
var buf bytes.Buffer
44
45
45
46
for i , s := range ss {
47
+ // ss 索引号为偶数的元素,不需要替换
46
48
if i % 2 == 0 {
47
49
buf .WriteString (s )
48
50
continue
49
51
}
50
52
51
- if s == entries [i / 2 ].source {
52
- buf .WriteString (entries [i / 2 ].target )
53
+ // ss 索引号为奇数的元素,需要检查是否要替换
54
+ if s == es [i / 2 ].source {
55
+ buf .WriteString (es [i / 2 ].target )
53
56
} else {
54
57
buf .WriteString (s )
55
58
}
0 commit comments