题目
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
题目大意
给定字符串,将每个单词逐字符逆置,返回新字符串。
注意:字符串中单词之间有且只有1个空格分开。
思路
代码
reverseWords.go
package _557_Reverse_Words3
import "strings"
func ReverseWord(s string) string {
runes := []rune(s)
for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
runes[from], runes[to] = runes[to], runes[from]
}
return string(runes)
}
func ReverseWords(s string) string {
wordArr := strings.Split(s, " ")
var ret string
length := len(wordArr)
for i := 0; i < length; i++ {
reverseWord := ReverseWord(wordArr[i])
if 0 == i {
ret = ret + reverseWord
} else {
ret = ret + " " + reverseWord
}
}
return ret
}
测试
reverseWords_test.go
package _557_Reverse_Words3
import "testing"
func TestReverseWords(t *testing.T) {
ret := ReverseWords("Let's take LeetCode contest")
want := "s'teL ekat edoCteeL tsetnoc"
if ret == want {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", want, ret)
}
}
有疑问加站长微信联系(非本文作者)
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)