luoheng
10/6/2019 - 11:38 AM

reverseWords

func reverse(s []byte, start, end int) {
    for start < end {
        s[start], s[end] = s[end], s[start]
        start++
        end--
    }
}

func reverseWords(s string) string {
    words := []byte(s)
    start := 0
    for end, word := range words {
        if word == ' ' {
            reverse(words, start, end-1)
            start = end + 1
        }
    }
    reverse(words, start, len(words)-1)
    return string(words)
}