[With Golang Brush Leetcode 6] 557. Reverse Words in a String III

Source: Internet
Author: User
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)}}  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.