Post

Created by @nathanedwards
 at November 5th 2023, 12:00:46 am.

Question:

/**
 * Write a Java method called `reverseWords` that takes in a String sentence and returns a new String with the words in reverse order. 
 * A word is defined as a sequence of non-space characters. The sentence will contain at least one word.
 * 
 * For example, if the input sentence is "Hello world, how are you?", the expected output would be "you? are how world, Hello".
 *
 * You may assume that the input sentence does not have leading or trailing spaces and the words are separated by spaces.
 *
 * Your solution should have a time complexity of O(n), where n is the length of the sentence.
 */

public class StringManipulation {

    public static String reverseWords(String sentence) {
        // Implementation goes here
    }
}

Answer:

/**
 * To solve this problem, we can follow these steps:
 * 1. Split the input sentence into an array of strings using the `split` method with space (" ") as the delimiter.
 * 2. Create an empty string called `result` to store the reversed words.
 * 3. Iterate over the array of words in reverse order.
 * 4. Append each word followed by a space to the `result` string.
 * 5. Finally, return the `result` string after trimming any trailing spaces.
 */

public static String reverseWords(String sentence) {
    String[] words = sentence.split(" ");
    StringBuilder result = new StringBuilder();

    for (int i = words.length - 1; i >= 0; i--) {
        result.append(words[i]).append(" ");
    }

    return result.toString().trim();
}