0

Given a String with words.Reverse words of String.

Sample Input 1

Hello World

Sample Output

World Hello

MyApproach

To reverse words I first counted how many spaces are there.After that I stored their space index in an array.Using lastIndex, I printed the last elements of the array.After that I printed the last 2 words of the array.

static String reverseWords(String inputString)
 {
    int l1=inputString.length();
    int count=1;
    for(int i=0;i<l1;i++)
    {
        char ch=inputString.charAt(i);
        if(ch==' ')
        {
            count++;
        }
    }
     
    int k=0;
    int[] spaceindex=new int[count];
    spaceindex[0]=0;
    k++;
    for(int i=0;i<l1;i++)
    {
        char ch=inputString.charAt(i);
        if(ch==' ')
        {
            spaceindex[k++]=i+1;
        }
    }
    
    int p=spaceindex.length-1;
    String strnew="";
    for(int j=spaceindex[p];j<l1;j++)
    {
        char c=inputString.charAt(j);
        strnew=strnew+c;
    }
    

    p--;
    while(p>=0)
    {
         for(int j=spaceindex[p];;j++)
            {
             
              char c=inputString.charAt(j);
               if(c==' ')
               {
                   break;
               }
               strnew=strnew+c;
                
            }   
         
    }
   return strnew;   
}

InputParameters     ActualOutput                        Expected Output

Hello World         WorldHelloWorldHello(Infinite loop) WorldHello

@Edit I asked Why the code I wrote is wrong.I tried without using any inbuilt functions(which was necessary for me).In that way I think It is not Duplicate Ans according to me.

Can anyone guide me what went wrong in my code.

Community
  • 1
  • 1
Jason arora
  • 550
  • 3
  • 8
  • 22

5 Answers5

1

Simple solution :

public static void main(String[] args) {

    String x = "Hello World";
    String[] xArray = x.split(" ");
    String result = "";

    for (int i = xArray.length - 1; i >= 0; i--) {
        result += xArray[i] + " ";
    }
    System.out.println(result.trim()); // World Hello
   }
Ahmad Alkhatib
  • 1,230
  • 2
  • 14
  • 31
1

The issue within your code was the while loop:

 while(p>=0) {
        strnew = strnew + " ";
        for(int j=spaceindex[p];;j++) {
           char c=inputString.charAt(j);
           if(c==' '){
              break;
           }
           strnew=strnew+c;
        }   
        p--;
 }

Adding the p-- will prevent the loop for occurring infinitely. Also inserting the strnew = strnew + " "; after the while loop ensures a space in between each word.

Sacert
  • 129
  • 7
  • I think your Ans is perfect.Because you checked the code.+1 for that.Other Ans were correct obviously but They are for reference to make my hardcode a bit easy.Thank you for you work. – Jason arora Dec 06 '15 at 13:09
1

It's possible without using another arrays, splits or any additional strucure.

Having array of characters ( convert if needed as String is immutable), first reverse all characters in the array. Secondly loop over spaces and for each word reverse characters in the word.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
1

You can use a StringTokenizer to convert the string into tokens or String.split function. You can push this collection into a Stack and extract the elements in a reverse order. To join the strings back you could use a StringBuilder or a StringBuffer.

To do this more efficiently you could convert the string to a character array and StringBuilders

String myString = "Here is the String";
char[] myChars = myString.toCharArray();

StringBuilder word = new StringBuilder();
StringBuilder newString = new StringBuilder();
for(int i = myChars.length - 1; --i >= 0;) {
   char c = myChars[i];
   if(c == ' ') {
       newString.append(c);
       newString.append(word);
       word = new StringBuilder();
   } else {
       word.append(c);
   }
}
Akshay Gehi
  • 362
  • 1
  • 12
1

I would base an implementation on String.lastIndexOf(int) and String.substring(int, int). I'd got with a StringBuilder to construct the output "sentence" and a while loop to iterate the words in reverse order. Something like,

static String reverseWords(String in) {
    StringBuilder sb = new StringBuilder(in.length());
    int space;
    while ((space = in.lastIndexOf(' ')) > 0) {
        sb.append(in.substring(space + 1, in.length())).append(' ');
        in = in.substring(0, space);
    }
    sb.append(in);
    return sb.toString();
}

Which I tested with your provided sample

public static void main(String[] args) {
    System.out.println(reverseWords("Hello World"));
}

Getting (as expected)

World Hello
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249