So, I assume that you are learning / practicing java and that there is a high risk of the homework question ... This means that you will love or hate this answer ...
If you look at the source code of a String object, you will find something like this inside:
private final char value[]; //this stores the String characters
The first step is to get this value [] with:
char[] myChars = str.toCharArray();
Pay attention to the implementation of the function (from openjdk-7 ), it returns a copy of the array, not the original one, since String objects are immutable.
public char[] toCharArray() { char result[] = new char[count]; getChars(0, count, result, 0);
Now that we have myChars
, we can play with it and get the result in linear time O (n)!
public static String reverseWordByWord(String str) { char[] myChars = str.toCharArray(); int stringLen = myChars.length; int left = 0, right = 0; for(int index = 0; index < stringLen; index++) { if(chars[index] == ' ') {
And here is the inverse function:
private static void reverse(char[] chars, int left, int right) { while(left < right) {
Now, just for fun, you might want to try to get the following result, and perhaps you will get this exact question from some interviewer who once completed a fantasy:
world new brave hello