Reverse Words in a String

Given an input string, reverse the string word by word.

Example:

Input: "the sky is blue",
Output: "blue is sky the".

Note:

  • A word is defined as a sequence of non-space characters.

  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.

  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve itin-place_in_O(1) space.

Topics: Two Pointers, String

Analysis

It actually reminds me of the string rotation problem , which could be solved by multi-step reversal of the string as well. The function void reverseWords(char[] a, int n), which is very much similar to what could be used in Max Consecutive Ones problem.

Two Pointers to the MAX.

Multi-reversal

        // step 1. clean up spaces
        char[] a = cleanSpaces(c, m);
        int n = a.length;
        // step 2. reverse the whole string
        reverse(a, 0, n - 1);
        // step 3. reverse each word
        reverseWords(a, n);

The void reverseWords(char[] a, int n) and char[] cleanSpaces(char[] a, int n) as well as void reverse(char[] a, int i, int j) all utilizes two pointers technique to remove spaces and reverse string.

Solution

Adapted Version - Two Pointers + multi-reversal: O(n) time, O(1) space (6ms)

Multi-reverse + Two Pointers - O(n) time, O(1) space (7ms)

https://leetcode.com/problems/reverse-words-in-a-string/discuss/47720/Clean-Java-two-pointers-solution-(no-trim(-)-no-split(-)-no-StringBuilder\

Using String operations trim(), split()- (65ms AC)

https://leetcode.com/problems/reverse-words-in-a-string/discuss/47706/My-accepted-Java-solution

Last updated

Was this helpful?