我有一个问题陈述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]
我的疑问是,如果在函数中,切片被修改,那么在调用函数中,为什么切片没有给出正确的结果?此外,任何更好地理解(和底层)的文章都将非常有帮助。slicesarray
牧羊人nacy
慕森王
慕田峪7331174
相关分类