为了账号安全,请及时绑定邮箱和手机立即绑定

删除字符串切片中的相邻重复项

删除字符串切片中的相邻重复项

Go
qq_花开花谢_0 2022-08-30 21:13:24
我有一个问题陈述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
查看完整描述

3 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

func removeAdjacentDuplicate 将切片“就好像”它是对 tempData 的引用一样


main() 中 tempData 的容量和长度在程序的生命周期内保持不变


在 removeAdjacentDuplicate func 中,每次找到一个 dupe 时,“ghi”的最终值就会从末尾移动到末尾 - 1。因此,在切片末尾的记忆中,有重复的“ghi”


当控件返回到 main 时,程序将打印出现在已修改的切片 tempData。因为它是以类似于对函数的引用的方式传递的,所以修改的是此内存。函数调用未创建内存的副本


您可以通过在程序运行时查看 cap() 和 len() 来查看此行为


package main


import (

        "fmt"

)


func main() {

        tempData := []string{"abc", "abc", "abc", "def", "def", "ghi"}

        removeAdjacentDuplicates(tempData)

        fmt.Println(tempData,cap(tempData),len(tempData))

}


func removeAdjacentDuplicates(data []string) {

        for j := 1; j < len(data); {

                if data[j-1] == data[j] {

                        data = append(data[:j], data[j+1:]...)

        fmt.Println(data,cap(data),len(data))

                } else {

                        j++

                }

        }

        fmt.Println(data, cap(data),len(data))

}


查看完整回答
反对 回复 2022-08-30
?
慕森王

TA贡献1777条经验 获得超3个赞

在代码中,想要改变在参数中传递的 slcie。这实际上是不可能的。removeAdjacentDuplicates


此函数应返回新切片,就像返回一样。append


func removeAdjacentDuplicates(data []string) []string{

    for j := 1; j < len(data); {

        if data[j-1] == data[j] {

            data = append(data[:j], data[j+1:]...)

        } else {

            j++

        }

    }

    return data

}

如果您确实想改变参数,这是可能的,但您需要传递指向切片的指针*[]string


查看完整回答
反对 回复 2022-08-30
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

试试这个功能:


func deleteAdjacentDuplicate(slice []string) []string {

    for i := 1; i < len(slice); i++ {

        if slice[i-1] == slice[i] {

            copy(slice[i:], slice[i+1:]) //copy [4] where there is [3, 4] => [4, 4]

            slice = slice[:len(slice)-1] //removes last element

            i-- //avoid advancing counter

        }

    }

    return slice

}


查看完整回答
反对 回复 2022-08-30
  • 3 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号