Understanding the Problem
We are given a string that contains words separated by spaces. However, the string may contain extra spaces — multiple spaces between words, or leading and trailing spaces. Our task is to reverse the order of the words and return a properly formatted string: the words should be in reverse order, and there should be exactly one space between them, with no leading or trailing spaces.
Step-by-Step Solution with Example
Let’s take the example string:
{
"array": [" the sky is blue "],
"showIndices": false
}
Step 1: Trim the String
We first remove the leading and trailing spaces from the string.
{
"array": ["the sky is blue"],
"showIndices": false
}
Step 2: Split the String by Spaces
Next, we split the string using space as the delimiter. This gives us an array of substrings. Some of these may be empty due to multiple spaces.
{
"array": ["the", "", "sky", "is", "blue"],
"showIndices": false
}
Step 3: Filter Out Empty Strings
We now remove the empty strings from the array, keeping only the valid words.
{
"array": ["the", "sky", "is", "blue"],
"showIndices": false
}
Step 4: Reverse the List of Words
We reverse the list so the words appear in reverse order.
{
"array": ["blue", "is", "sky", "the"],
"showIndices": false
}
Step 5: Join Words with a Single Space
Finally, we join the reversed words using a single space to form the final output string.
{
"array": ["blue is sky the"],
"showIndices": false
}
Edge Cases
- Empty String: Return an empty string.
- String with Only Spaces: After trimming and filtering, return an empty string.
- String with One Word: Return the trimmed single word as-is.
- Multiple Spaces Between Words: Ensure only one space between words in the final output.
Finally
This approach ensures a clean and efficient transformation of the input string. By trimming spaces, filtering out empty tokens, reversing the order, and rejoining the words, we handle both normal and edge cases gracefully. This makes the solution beginner-friendly and robust for real-world usage.
Comments
Loading comments...