Tuesday, December 4, 2012

Reverse Words In A Char Array - Java

I'm back again with a Java post in my blog :-)

Recently I came across an interview question - "Given a statement in char[], reverse the order of words in that statement without using any extra temporary char[] or String functions". Here is my solution for this question.

There will be N - 1 Runs for reversing a statement which has N words in
it.

1st Run will move the First word in statement to make it as Last Word and move the remaining space from first position before the word just moved.

2nd Run will move the now First word in statement to make it as 2nd last word
and the remaining space from first position before the word just moved.

So, (N-1)th Run will move the now First word in statement to make it as Nth
last word (i.e., Second Word) and the space before it from first position.

5 comments:

We have a character array such as follows char –(a, ,c,a,t, ,f,a,l,l,s, ,d,o,w,n, ,a,n,d, ,m,e,o,w,s}

Can you please provide me with an “In-place” algorithm to efficiently reverse this character array. By “In-Place” I mean a solution which will not create any extra resources e.g. by creating a second character array.

So the required output would be {m,e,o,w,s, ,a,n,d, ,d,o,w,n, ,f,a,l,l,s, ,c,a,t, ,a}

In your case you take I/P as a String and converting this into Char Array. how about the taking char[] test = {a, ,c,a,t, ,f,a,l,l,s, ,d,o,w,n, ,a,n,d, ,m,e,o,w,s}; as a I/P value and get the O/P as {m,e,o,w,s, ,a,n,d, ,d,o,w,n, ,f,a,l,l,s, ,c,a,t, ,a}.