Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 8e9e92b

Browse files
aQuaaQua
aQua
authored and
aQua
committed
833 finish
1 parent 0907b9a commit 8e9e92b

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

Algorithms/0833.find-and-replace-in-string/find-and-replace-in-string.go

+20-17
Original file line numberDiff line numberDiff line change
@@ -10,46 +10,49 @@ type entry struct {
1010
source, target string
1111
}
1212

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{
1717
idx: indexes[i],
1818
source: sources[i],
1919
target: targets[i],
2020
}
2121
}
2222

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
2526
})
2627

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)
3030

3131
end := 0
32-
for i := range entries {
32+
// 按照 es 分割 Str
33+
for _, e := range es {
3334
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])
3738
}
38-
39+
// 尾部有剩余,也要加入 ss
3940
if end < size {
40-
ss = append(ss, S[end:])
41+
ss = append(ss, Str[end:])
4142
}
4243

4344
var buf bytes.Buffer
4445

4546
for i, s := range ss {
47+
// ss 索引号为偶数的元素,不需要替换
4648
if i%2 == 0 {
4749
buf.WriteString(s)
4850
continue
4951
}
5052

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)
5356
} else {
5457
buf.WriteString(s)
5558
}

0 commit comments

Comments
 (0)