2 回答

TA貢獻1906條經驗 獲得超3個贊
有多種方法可以實現這一目標。一個是這樣的:
import "strings"
func Dedup(input string) string {
unique := []string{}
words := strings.Split(input, " ")
for _, word := range words {
// If we alredy have this word, skip.
if contains(unique, word) {
continue
}
unique = append(unique, word)
}
return strings.Join(unique, " ")
}
func contains(strs []string, str string) bool {
for _, s := range strs {
if s == str {
return true
}
}
return false
}

TA貢獻1851條經驗 獲得超3個贊
package main
import "fmt"
func removeDuplicates(arr []string) []string {
words_string := map[string]bool{}
for i:= range arr {
words_string[arr[i]] = true
}
desired_output := []string{} // Keep all keys from the map into a slice.
for j, _ := range words_string {
desired_output = append(desired_output, j)
}
return desired_output
}
func main() {
arr := []string{"hi", "hi", "hi", "ho", "ho", "hello"}
fmt.Println(arr)
desired_output := removeDuplicates(arr) // Remove the duplicates
fmt.Println(desired_output)
}
- 2 回答
- 0 關注
- 169 瀏覽
添加回答
舉報