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

对具有相同文本的字符串片段进行编号

对具有相同文本的字符串片段进行编号

Go
Qyouu 2023-02-21 12:50:55
我有一段字符串包含一些具有相同文本的元素,例如: [apple, banana, apple, peer, apple] 我想做的是以这种方式按编号更新具有相同文本的字符串的名称: [apple, banana, apple2, peer, apple3] 我如何在一段字符串中执行此操作?
查看完整描述

1 回答

?
幕布斯6054654

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

这应该以非常有效的方式解决您的问题:O(N) package main


import (

    "fmt"

    "strconv"

)

func main() {

    testStringSlice := []string{"apple", "banana", "apple", "peer", "apple"}

    outputStringSlice := numberItems(testStringSlice)

    fmt.Println(outputStringSlice)

}


func numberItems (arr []string) []string{

    m := make(map[string]int)

    for idx, item := range arr {

            if count, ok := m[item]; ok {

                    m[item] = count + 1

                    arr[idx] = item + strconv.Itoa(m[item])

            } else {

                    m[item] = 1

            }

    }

    return arr

}


查看完整回答
反对 回复 2023-02-21
  • 1 回答
  • 0 关注
  • 49 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信