Back to Leetcode Go

557. Reverse Words in a String III

website/content.en/ChapterFour/0500~0599/0557.Reverse-Words-in-a-String-III.md

1.7.971.3 KB
Original Source

557. Reverse Words in a String III

Problem

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.

Problem Summary

Given a string, you need to reverse the order of characters in each word in the string while still preserving whitespace and the initial word order. Note: In the string, each word is separated by a single space, and there will not be any extra spaces in the string.

Solution Approach

  • Reverse the string, requiring reversal by small strings separated by spaces.
  • This is an easy problem. Simply reverse each word separated by spaces according to the problem statement.

Code

go

package leetcode

import (
	"strings"
)

func reverseWords(s string) string {
	ss := strings.Split(s, " ")
	for i, s := range ss {
		ss[i] = revers(s)
	}
	return strings.Join(ss, " ")
}

func revers(s string) string {
	bytes := []byte(s)
	i, j := 0, len(bytes)-1
	for i < j {
		bytes[i], bytes[j] = bytes[j], bytes[i]
		i++
		j--
	}
	return string(bytes)
}