##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/557.html

# 557. Reverse Words in a String III

Easy

## Description

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.

## Solution

Since words are split by spaces, find the start index and the end index of each word, and reverse the characters from the start index and the end index.

• public class Reverse_Words_in_a_String_III {

// ref: https://leetcode.com/articles/reverse-words-in-a-string-iii/
public class Solution {
public String reverseWords(String input) {
final StringBuilder result = new StringBuilder();
final StringBuilder word = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) != ' ') {
word.append(input.charAt(i));
} else {
result.append(word.reverse());
result.append(" ");
word.setLength(0);
}
}
result.append(word.reverse()); // @note: last one
return result.toString();
}
}

public class Solution2 {
public String reverseWords(String s) {
String words[] = s.split(" ");
StringBuilder res = new StringBuilder();
for (String word : words) {
res.append(new StringBuffer(word).reverse().toString() + " ");
}
return res.toString().trim();
}
}
}

############

class Solution {
public String reverseWords(String s) {
StringBuilder res = new StringBuilder();
for (String t : s.split(" ")) {
for (int i = t.length() - 1; i >= 0; --i) {
res.append(t.charAt(i));
}
res.append(" ");
}
return res.substring(0, res.length() - 1);
}
}

• class Solution {
public:
string reverseWords(string s) {
for (int i = 0, n = s.size(); i < n; ++i) {
int j = i;
while (++j < n && s[j] != ' ')
;
reverse(s.begin() + i, s.begin() + j);
i = j;
}
return s;
}
};

• class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join([t[::-1] for t in s.split(' ')])

############

class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s = s.split()
for i, word in enumerate(s):
s[i] = word[::-1]
return " ".join(s)


• func reverseWords(s string) string {
t := []byte(s)
for i := 0; i < len(t); i++ {
j := i
for j < len(t) && t[j] != ' ' {
j++
}
for st, ed := i, j-1; st < ed; st, ed = st+1, ed-1 {
t[st], t[ed] = t[ed], t[st]
}
i = j
}
return string(t)
}

• function reverseWords(s: string): string {
return s
.split(/\s+/)
.map(str => {
let res = '';
for (const c of str) {
res = c + res;
}
return res;
})
.join(' ');
}


• class Solution {
/**
* @param String $s * @return String */ function reverseWords($s) {
$sArr = explode(' ',$s);
for ($i = 0;$i < count($sArr);$i++) {
$sArr[$i] = strrev($sArr[$i]);
}
return implode(" ", \$sArr);
}
}

• impl Solution {
pub fn reverse_words(s: String) -> String {
s.split(' ')
.map(|s| s.chars().rev().collect::<String>())
.collect::<Vec<_>>()
.join(" ")
}
}