Reverse Words in a String III
Turn the letters of every word around while the words keep their places, by swapping each word's letters from both ends.
Given a string s
Example 1
Output: "s'teL ekat a gnidoc tsetnoc"
Example 2
Output: "rM gniD"
The Idea
Read the words "Mr Ding" backwards, one word at a time. "Mr" reads "rM" and "Ding" reads "gniD", but "Mr" still comes first and the space stays between them. That is exactly the answer to Example 2: only the letters inside each word turn around.
Example 1 works the same way. "take" becomes "ekat", and the one-letter word "a" stays "a", because a single letter reads the same both ways. The apostrophe in "Let's" is just another character, so "Let's" becomes "s'teL".
A program does not see words, though. It sees one row of characters, numbered from 0. So two questions come up: how does it know where one word ends and the next begins, and how does it turn one word around inside that row? Look at the picture below.
The row labelled "before" shows "Mr Ding" at indexes 0 to 6. The space at index 2 closes the first word, which runs from 0 to 1. The second word has no space after it, but the string ends at index 7, and that closes it just the same. So a word is everything between two boundaries, and a boundary is either a space or the end of the string.
Once a word's two ends are known, turning it around takes a few swaps. The row labelled "reversing Ding" starts with one marker, lohi
Using two markers that start at the two ends and walk toward each other is called the two-pointer technique. Here it runs once for every word, and each run only touches the letters between that word's two boundaries.
Solution Approach
The code needs answers to four questions: where the letters can be changed, how to find each word's boundaries, what to do with the last word, and how to reverse one word.
Changing letters in a Java string
Can we swap letters inside sStringcharcs.toCharArray()cnew String(c)
Finding each word's boundaries
How does the code find where a word starts and ends? It keeps startendendstartend - 1end + 1
Handling the last word
What about the last word, which has no space after it? The loop that moves endc.lengthend == c.lengthc[end]
That one extra step past the end matters. A loop that stops at end < c.length
Reversing one word
How does one word get turned around? A small helper, reverselohilohi
A shorter version with split
As an alternative, Java can do the cutting and reversing for us. s.split(" ")new StringBuilder(word).reverse()String.join(" ", words)
Java Solution
Here is what reverseWords
- First, copy the string into a
arraychar withc , so letters can be swapped.s.toCharArray() - Set
to 0, the first letter of the first word.start - Move
with aend loop from 0 up to and includingfor . Whenc.length equalsend orc.length is a space, the current word isc[end] .c[start .. end - 1] - Reverse that word with
. Inside the helper,reverse(c, start, end - 1) andlo swap letters through a temporaryhi and move inward until they meet. Back in the loop, settmp , just after the space.start = end + 1 - When the loop is done, return
.new String(c)
The main
public class ReverseWordsInStringIII {
public static String reverseWords(String s) {
char[] c = s.toCharArray();
int start = 0;
for (int end = 0; end <= c.length; end++) {
if (end == c.length || c[end] == ' ') {
reverse(c, start, end - 1); // the word is c[start .. end-1]
start = end + 1; // next word begins after the space
}
}
return new String(c);
}
private static void reverse(char[] c, int lo, int hi) {
while (lo < hi) {
char tmp = c[lo];
c[lo] = c[hi];
c[hi] = tmp;
lo++;
hi--;
}
}
public static void main(String[] args) {
System.out.println("\"" + reverseWords("Let's take a coding contest") + "\"");
System.out.println("\"" + reverseWords("Mr Ding") + "\"");
System.out.println("\"" + reverseWords("abc") + "\"");
System.out.println("\"" + reverseWords("a b c") + "\"");
System.out.println("\"" + reverseWords("") + "\"");
}
}
Running it prints:
"s'teL ekat a gnidoc tsetnoc"
"rM gniD"
"cba"
"a b c"
""
"Mr Ding" comes out as "rM gniD""cba"
The fourth line, "a b c"reverselohiendc.lengthreverse(c, 0, -1)""
Complexity
The work is one pass of end
- Time: O(n), where n is the number of characters in
.s visits each character once, and since words never overlap, all theend calls together swap each letter at most once.reverse - Space: O(n), because
copies all n characters. A Java string cannot be changed in place, so the answer needs a new copy of that size anyway.toCharArray()
To reverse the order of the words instead of their letters, see