...

/

Reverse Words in a String

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.

  • 11 \leq sentence.length 104\leq 10^4

Examples

canvasAnimation-image
1 / 4

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

1.

What is the output if the following sentence is given as an input?

“The quick brown fox jumped over a lazy dog”.

A.

“lazy dog a over fox jumped brown quick The”

B.

“dog lazy over a jumped fox brown quick The”

C.

“dog lazy jumped jumped fox brown quick The”

D.

“dog lazy a over jumped fox brown quick The”


1 / 4

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.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

Java
usercode > Solution.java
import java.util.*;
public class Solution {
public static String reverseWords(String sentence) {
// Replace this placeholder return statement with your code
return "";
}
}
Reverse Words in a String

Access this course and 1200+ top-rated courses and projects.