[用Golang刷LeetCode之 6] 557. Reverse Words in a String III

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

題目

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_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}

測試

reverseWords_test.go

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)    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.