題目
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
解法
import (
"strings"
)
func reverseWords(s string) string {
split := strings.Split(s, " ")
res := ""
for _, v := range split {
res = res + reverse(v) + " "
}
return strings.Trim(res, " ")
}
func reverse(s string) string {
var str string
for _, v := range s {
str = string(v) + str
}
return str
}
- 加些測試,看看結果是不是如預期
func Test_reverseWords(t *testing.T) {
assert.Equal(t, "s'teL ekat edoCteeL tsetnoc", reverseWords("Let's take LeetCode contest"))
}