Reverse Words in String III
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
Single word reversed
Empty
Two words reversed
Each word reversed
Single chars unchanged
Algorithm Flow
Solution Approach
Split the string into words, reverse each word individually, and join them back with spaces.
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
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();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
