Clockwork Clockwork - 6 months ago 8
Java Question

Reversing the words in a sentence

I'm trying to reverse the words in a string. This if the input is

The quick brown fox


the expected output is,

fox brown quick The


I'm following a simple algortihm, reverse the whole sentence and then reverse the words back.
This is my code.

public static void reverseWords(char[] s) {
reverse(s);
int start = 0;
for (int i = 0; i < s.length ; i++) {

if(s[i] == ' '){
indexedReverse(s, start, i);
start = i+1;
}
}

}

private static void reverse(char[] s){
int len = s.length;
for(int i=0; i< len/2 ; i++){
char temp = s[i];
s[i] = s[len -1 -i];
s[len - 1- i] = temp;
}
}

private static void indexedReverse(char[] s, int start, int end){

for (int j = start; j <end/2; j++){
char temp = s[j];
s[j] = s[end - 1 - j];
s[end -1 -j] = temp;
}
}

public static void main(String[] args) {

String str = "The quick brown fox";
char[] s = str.toCharArray();
reverseWords(s);
String newStr = new String(s);
System.out.println(newStr);
}


The issue is that the indexedReversed() function goes into the for loop only once for the first word and then it skips the loop completely. What am I doing wrong here.
The output I'm getting is,

fox nworb kciuq ehT

Answer

It looks like your indexedReverse function doesn't take into account the relative position of the beginning of the word.

        for (int i = 0; i < s.length ; i++) {

            if(s[i] == ' '){
                indexedReverse(s, start, i);
                start = i+1;
            }
        }

    }

    private static void reverse(char[] s){
        int len = s.length;
        for(int i=0; i< len/2 ; i++){
            char temp = s[i];
            s[i] = s[len -1 -i];
            s[len - 1- i] = temp;
        }
    }

    private static void indexedReverse(char[] s, int start, int end){
        int newEnd = start+(end-start)/2; // it worked for the first word because start = 0
        for (int j = start; j <newEnd; j++){
            char temp = s[j];
            s[j] = s[end - 1 - j];
            s[end -1 -j] = temp;
        }
    }

    public static void main(String[] args) {

        String str = "The quick brown fox";
        char[] s = str.toCharArray();
        reverseWords(s);
        String newStr = new String(s);
        System.out.println(newStr);
    }
Comments