#151
Reverse Words in a String
Medium Split & rebuild
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Reverse the order of words in a string. Remove leading, trailing and repeated spaces.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: reverse the word order and clean up spaces.
Why this works: split on runs of spaces, then join the words from last to first with single spaces.
Example: " the sky is blue "
words: [the, sky, is, blue]→ "blue is sky the"
✦Hints open one at a time
trim() then split on one or more spaces with "\\s+".
Join the words from last to first with a single space.
↗Approach
Split into words, then append them in reverse order to a StringBuilder with single spaces in between. (A manual two-pointer scan from the end gives the same result without regex.)
</>Solution (Java)
class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]);
if (i > 0) sb.append(' ');
}
return sb.toString();
}
}
!Common mistake
split(" ") on raw input produces empty strings for repeated spaces.
Complexity
- Time: O(n).
- Space: O(n).
Topic: Strings
🎬 Episodes 16–20: video coming soon