This is a creation in Article, where the information may have evolved or changed.
Topic
Given a string, need to reverse the order of characters in each word within a sentence while still preserving WhiteSpa CE and initial word order.
Example 1:
Input: "Let's take Leetcode contest"
Output: "s ' TeL ekat edocteel Tsetnoc"
Note: In the string, each of the word is separated by a single space and there won't is a extra space in the string.
Main topic
Returns a new string, given a string, by reversing each word verbatim.
Note: There are only 1 spaces separated between words in a string.
Ideas
Code
Reversewords.go
package _557_Reverse_Words3import "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}
Test
Reversewords_test.go
The package _557_reverse_words3import "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)}}