Reverse Words in a String
Try to solve the Reverse Words in a String problem.
Statement
You are given a string sentence
that may contain leading or trailing spaces, as well as multiple spaces between words. Your task is to reverse the order of the words in the sentence without changing the order of characters within each word. Return the resulting modified sentence
as a single string with words separated by a single space, and no leading or trailing spaces.
Note: A word is defined as a continuous sequence of non-space characters. Multiple words separated by single spaces form a valid English sentence. Therefore, ensure there is only a single space between any two words in the returned string, with no leading, trailing, or extra spaces.
Constraints:
The
sentence
contains English uppercase and lowercase letters, digits, and spaces.There is at least one word in a
sentence
.sentence.length
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Reverse Words in a String
What is the output if the following sentence is given as an input?
“The quick brown fox jumped over a lazy dog”.
“lazy dog a over fox jumped brown quick The”
“dog lazy over a jumped fox brown quick The”
“dog lazy jumped jumped fox brown quick The”
“dog lazy a over jumped fox brown quick The”
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
import java.util.*;public class Solution {public static String reverseWords(String sentence) {// Replace this placeholder return statement with your codereturn "";}}