This community-built FAQ covers the “Reverse Words” code challenge in Java. You can find that challenge here, or pick any challenge you like from our list.
Top Discussions on the Java challenge Reverse Words
There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
You can also find further discussion and get answers to your questions over in Language Help.
Agree with a comment or answer? Like () to up-vote the contribution!
I initially put in some sanity checks for test cases with the 3 if statements at the top in case of input being “”/empty, or for when input is one only string, or input is null.
my code ran successfully immediately, but could only pass 1/5 test cases until I used the trim() to remove all leading and trailing white space characters on the return statement line. It took me a whole lot of hours to figure out why my code only passed 1/5 test cases.
The use of the StringBuilder object to build a new string is more efficient and conserves memory instead of using an array to manipulate the words, or using a String variable which is immutable and creates a new object each time you use it.
public class WordReverser {
public static void main(String args) {
System.out.print(wordReverser(“Codecademy rules”));
}
public static String wordReverser(String input) {
// Write your code here
if(input.equals(“”)) return “”;
if(input.length() < 1 ) return “”;
if(input.length() == 1 ) return input;
StringBuilder reverse = new StringBuilder();
String[] arr = input.split(" ");
int len = arr.length;
for(int i = len-1; i >= 0; i-- ) {
reverse.append(arr[i]).append(" ");
}
return reverse.toString().trim();
O(m + n) - I stripped out the loop-internal concatenations present in many of the other solutions
// Java code to illustrate initialization
// of ArrayList using add() method
import java.util.*;
public class WordReverser {
public static void main(String[] args) {
System.out.print(wordReverser("Codeacademy rules"));
}
public static String wordReverser(String input) {
// split string on spaces and save each word as an element in an array
String[] words = input.split(" ");
// copy all the elements to a Stack
Stack<String> wordsStack = new Stack<>();
Collections.addAll(wordsStack, words);
String answer = "";
// iterate over all of the stack objects and pop each one into the string in the correct order (reverse)
answer = wordsStack.pop();
while (wordsStack.size() >= 1){
answer += " " + wordsStack.pop();
}
return answer;
}
}
I tried to come up with a way that does not include String.join nor adding a bunch of strings with a loop and does not use StringBuilder.
I made the input into an array of chars and used variables to keep track of the index where the word starts and another for where the space character following the word is.
public static String wordReverser(String input) {
char[] charray = input.toCharArray();
int length = charray.length;
char[] reversed = new char[length];
int h = 0;
for (int i = 0; i <= length; i++) {
// i used to iterate through chars and find space char
if ((i == length || charray[i] == ' ') && h <= i) {
// h is index of start of word to reverse
// i is index after end of word to to reverse
int j = 0; // to iterate through chars of word
int k = i - h; // length of word
while (j < k) {
// current word in original starts at h
// current word in reversed starts at length - i
reversed[length - i + j] = charray[h + j];
j++;
}
// insert space into reversed if needed:
if (i < length && charray[i] == ' ') {
reversed[length - i - 1] = ' ';
}
h = i + 1;
}
}
return new String(reversed);
}
I guess you could reverse the entire string first, and then reverse the letters in the words in that reversed string to get the same result.
Meaning a “composition” of functions
public static String reverseWordsOf(String input) { // reverses letters in each word
char[] charray = input.toCharArray();
int length = charray.length;
int h = 0;
for (int i = 0; i <= length; i++) {
if ((i == length || charray[i] == ' ') && h <= i) {
int j = h; // index of start of word to reverse
int k = i - 1; // index of end of word to to reverse
while (j < k) {
char temp = charray[k];
charray[k] = charray[j];
charray[j] = temp;
j++;
k--;
}
h = i + 1;
}
}
return new String(charray);
}
public static String reverseOf(String input) { // reverses characters in string
char[] charray = input.toCharArray();
int i = 0;
int j = charray.length - 1;
while (i < j) {
char temp = charray[j];
charray[j] = charray[i];
charray[i] = temp;
i++;
j--;
}
return new String(charray);
}
public static String wordReverser(String input) {
return reverseWordsOf(reverseOf(input));
}