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

miltonsun · · 910 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

题目

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

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:miltonsun

查看原文:[用Golang刷LeetCode之 6] 557. Reverse Words in a String III

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

910 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传