题解 | #第一个只出现一次的字符#

替换空格

http://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68

两步走

func replaceSpace(s string) string {
    // write code here
    // 遍历一遍字符串, 统计字符出现的位置
    if len(s) < 0 {
        return s
    }
    var cnt []int
    for i := 0; i < len(s); i++ {
        if s[i] == ' ' {
            cnt = append(cnt, i)
        }
    }
    // 从后往前插入,从前插入会破坏顺序
    for i := len(cnt) -1; i >= 0; i-- {
        p := cnt[i]
        s = s[:p] + "%20" + s[p+1:]
    }
    return s
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务