Wednesday, January 4, 2023
Reverse words in a string III
A function, given a string s
, to reverse the order of characters in each word
within a sentence while still preserving whitespace and initial word order.
Go
- Time complexity: - n is a length of a string
- Auxiliary space: - n is a length of a string
import "fmt"
func reverseWords(s string) string {
words := strings.Split(s, " ")
var reversedString string
for index, word := range words {
reversedString += reverseWord([]byte(word))
if index != len(words) - 1 {
reversedString += " "
}
}
return reversedString
}
func reverseWord(s []byte) string {
for i, j := 0, len(s)-1; i < j; i, j = i + 1, j - 1 {
s[i], s[j] = s[j], s[i]
}
return string(s)
}