Reverse Words in a String
Reverse the order of the words in a string, with exactly one space between them.
Given a string ss
Example 1
Output: "blue is sky the"
Example 2
Output: "world hello"
Explanation: the spaces at the start and end are dropped.
Example 3
Output: "example good a"
Explanation: the three spaces between "good" and "example" become one.
The Idea
Read a sentence backwards, one word at a time, and "the sky is blue" becomes "blue is sky the". The words themselves stay as they are; only their order changes. If every gap were a single space, you could cut the string at each space and read the pieces from last to first.
Examples 2 and 3 are not that tidy. " hello world ""a good example"
Start from the end, because the last word of sendstartstartend
In the row labelled "first word", enddstartendostart
So the words turn up in exactly the order the answer needs. The spaces of s
Solution Approach
Turning that idea into code means settling three things: whether to let the Java library split the string, how the two pointers find each word, and where the single spaces come from.
The library way
Can Java's Strings.trim()split("\\s+")"\\s+"
The pattern matters, though. With split(" ")"a good example""example good a"
Finding each word with two pointers
Where exactly does each word begin and end? ends.length() - 1startend
startstart + 1endstart
One space between words
How do we get exactly one space between words and none at the ends? We add every space ourselves and never take one from s
Java Solution
The method reverseWords
- First, create
, asb : a Java class that builds a string piece by piece without making a new string each time. Then setStringBuilder to the last index,end .s.length() - 1 - Run an outer loop while
. Inside it, a first inner loop movesend >= 0 left past any spaces. Ifend drops below 0, break out of the outer loop, because only spaces were left.end - Set
tostart , and a second inner loop movesend left until it reaches a space or -1.start - If
already holds a word, append one space. Then append the word withsb , which copies the characters from indexsb.append(s, start + 1, end + 1) up to, but not including,start + 1 .end + 1 - Set
toend , so the next round of the outer loop carries on left of the word just copied.start - When the outer loop ends, return
.sb.toString()
The main
public class ReverseWordsInString {
public static String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
int end = s.length() - 1;
while (end >= 0) {
while (end >= 0 && s.charAt(end) == ' ') {
end--; // skip spaces after the word
}
if (end < 0) {
break; // only spaces were left
}
int start = end;
while (start >= 0 && s.charAt(start) != ' ') {
start--; // move to the space before the word
}
if (sb.length() > 0) {
sb.append(' '); // one space between words
}
sb.append(s, start + 1, end + 1); // the word is s[start+1 .. end]
end = start;
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println("[" + reverseWords("the sky is blue") + "]");
System.out.println("[" + reverseWords(" hello world ") + "]");
System.out.println("[" + reverseWords("a good example") + "]");
System.out.println("[" + reverseWords(" ") + "]");
System.out.println("[" + reverseWords(" single ") + "]");
}
}
Running it prints:
[blue is sky the]
[world hello]
[example good a]
[]
[single]
Look at [world hello][example good a]" hello world "[]" "end
In the last line, [single]startsb
Complexity
The work is one walk from the right end of ssb
- Time: O(n), where n is the length of
.s andend only ever move left, so each of the n characters is checked at most twice, and each letter of a word is copied once.start - Space: O(n) for the result.
and the returned string hold at most n characters, and the two pointers are just two numbers.sb
To reverse the letters inside each word instead of the order of the words, see