{x}
blog image

Reverse Words in a String III

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

 

Example 1:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:

Input: s = "Mr Ding"
Output: "rM gniD"

 

Constraints:

  • 1 <= s.length <= 5 * 104
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.

Solution Explanation: Reverse Words in a String III

This problem requires reversing the order of characters within each word of a given string while preserving the original word order and spaces. The most efficient approach involves these steps:

  1. Split the String: Divide the input string into individual words using the space character (" ") as a delimiter. This can be achieved using built-in string manipulation functions like split() in Python, Java, Javascript, strings.Fields() in Go, or explode() in PHP.

  2. Reverse Each Word: Iterate through the array of words and reverse the characters within each word. String reversal can be efficiently done using built-in functions like reversed() in Python, StringBuilder.reverse() in Java, reverse() in C++, or by iterating through the characters and swapping them.

  3. Join the Words: Reconstruct the string by joining the reversed words back together, separated by spaces. Functions like join() in Python, Java, Javascript, strings.Join() in Go, or implode() in PHP are helpful for this step.

Time and Space Complexity Analysis

  • Time Complexity: O(n), where n is the length of the input string. This is because we iterate through the string once to split it into words, then iterate through the words again to reverse them, and finally iterate to join them. Each of these steps is linear in the length of the input.

  • Space Complexity: O(n) in the worst case. This is because, in the worst-case scenario, where the string consists of only one long word, we create a copy of the string when reversing it. In the average case where there are multiple shorter words, the space usage might be less, but it's still proportional to the length of the string.

Code Examples (with detailed explanations)

The provided code examples implement the solution in various programming languages. Let's delve into the logic of a few of them:

Python:

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

This Python solution is concise and efficient. s.split() splits the string into a list of words. The list comprehension (t[::-1] for t in s.split()) iterates through each word (t), reverses it using slicing [::-1], and creates a new list of reversed words. Finally, " ".join(...) joins the reversed words back into a string with spaces.

Java:

class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        for (int i = 0; i < words.length; ++i) {
            words[i] = new StringBuilder(words[i]).reverse().toString();
        }
        return String.join(" ", words);
    }
}

The Java solution uses s.split(" ") to split the string. Then, it iterates through each word, creating a StringBuilder object to reverse the word efficiently and converting it back to a String. Finally, String.join(" ", words) joins the reversed words.

C++:

class Solution {
public:
    string reverseWords(string s) {
        stringstream ss(s);
        string t;
        string ans;
        while (ss >> t) {
            reverse(t.begin(), t.end());
            ans += t;
            ans.push_back(' ');
        }
        ans.pop_back(); // Remove trailing space
        return ans;
    }
};

The C++ code uses a stringstream to efficiently handle word separation. The while loop reads words from the stream, reverses them using reverse(t.begin(), t.end()), and appends them to the ans string, adding spaces in between. The trailing space is removed at the end.

The other language examples (Go, TypeScript, Rust, Javascript, PHP) follow similar logic, adapting the specific string manipulation functions available in those languages. All of them achieve the same result with the same time and space complexity.