What are the common string reversal patterns in Java interviews, and which approach should you pick?
There are three different reversal questions, and they need three different answers.
The first one is reversing the characters. The answer is the method reverse on the class StringBuilder, or a loop over a character array.
The second one is reversing the order of the words, while keeping the letters inside each word the right way round. The answer is to split the text on the spaces, reverse the array of words, and join it back together.
The third one is checking whether a text is a palindrome, which means it reads the same forwards and backwards. The answer is to make a cleaned up copy of the text and compare it with its reverse.
So which approach should you pick? It depends on the question, and the common mistake is to use the wrong one. If the question says reverse the string, then you reverse the characters. If it says reverse the words, then you split first. If it says reverse the words and the letters in each word, then you do both.
The next question in this topic shows the two of them that people get wrong most often.