【发布时间】:2021-08-04 09:49:25
【问题描述】:
我有一个问题声明给write an in-place function to eliminate the adjacent duplicates in a string slice.
我想出了以下代码
func main() {
tempData := []string{"abc", "abc", "abc", "def", "def", "ghi"}
removeAdjacentDuplicates(tempData)
fmt.Println(tempData)
}
func removeAdjacentDuplicates(data []string) {
for j := 1; j < len(data); {
if data[j-1] == data[j] {
data = append(data[:j], data[j+1:]...)
} else {
j++
}
}
fmt.Println(data)
}
输出如下
[abc def ghi]
[abc def ghi ghi ghi ghi]
我的疑问是,如果在函数中修改了切片,那么在调用函数中,为什么切片没有给出正确的结果?
此外,任何能更好地理解slices(和底层array)的文章都会非常有帮助。
【问题讨论】:
-
另外,
data = append(data[:j], data[j+1:]...)正在复制大量数据(切片的其余部分),这可能会破坏性能。您可以稍微改变一下,并通过在适当的位置附加单个项目来避免它。