亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

刪除字符串切片中的相鄰重復項

刪除字符串切片中的相鄰重復項

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 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號