Code Logo

Reverse Words in String III

Published at25 Jul 2026
Medium 1 views
Like0

Given a string of words separated by single spaces, reverse the characters within each word while preserving the word order. Return the resulting string with words still separated by single spaces.

For example, reversing words in "Let's take LeetCode contest" produces "s'teL ekat edoCteeL tsetnoc". A single word "hello" becomes "olleh". An empty string returns "".

This problem is a variation of string reversal that operates at the word level. It teaches string splitting, individual word manipulation, and rejoining. It combines two fundamental operations: splitting and reversing.

The solution splits the string into words, reverses each word's characters, and joins them back with spaces. Each word is reversed by swapping characters from both ends moving inward.

Edge cases include an empty string (return ""), a single word (return its reverse), and words with punctuation (treated as part of the word).

Example Input & Output

Example 1
Input
"abc"
Output
"cba"
Explanation

Single word reversed

Example 2
Input
""
Output
""
Explanation

Empty

Example 3
Input
"hello world"
Output
"olleh dlrow"
Explanation

Two words reversed

Example 4
Input
"the sky is blue"
Output
"eht yks si eulb"
Explanation

Each word reversed

Example 5
Input
"a b c"
Output
"a b c"
Explanation

Single chars unchanged

Algorithm Flow

Recommendation Algorithm Flow for Reverse Words in String III

Solution Approach

Split the string into words, reverse each word individually, and join them back with spaces.

function reverseWords(s)
  words = split(s, " ")
  for i = 0 to length(words) - 1
    words[i] = reverse(words[i])
  return join(words, " ")

Split the input string on spaces to get an array of words. For each word, reverse the order of its characters. Finally, join the reversed words back into a string using single spaces. The reverse function can be implemented by swapping characters from both ends or using a built-in reverse.

Time complexity is O(n) where n is the total string length. Space complexity is O(n) for the words array and result.

Best Answers

java
class Solution {
    public String solution(String s) {
        String[] w=s.split(" ",-1);StringBuilder r=new StringBuilder();
        for(int i=0;i<w.length;i++){r.append(new StringBuilder(w[i]).reverse());if(i<w.length-1)r.append(' ');}
        return r.toString();
    }
}