fork download
  1.  
  2. /**
  3.  * In-place words reversal in a character array
  4.  * @author PRATEEK
  5.  */
  6. class ReverseWordsCharArray {
  7.  
  8. /**Reverse Words in an array
  9. */
  10. private static void reverseWords(char[] str) {
  11. if(str==null || str.length==0)
  12. return ;
  13.  
  14. String temp = new String(str);
  15. int len = str.length, l=0,r=0;
  16.  
  17. //Reverse the input array
  18. reverseArr(str, 0, str.length-1);
  19.  
  20. while(r<len && str[r] == ' ') //Skip initial Spaces, if any
  21. r++;
  22.  
  23. while(r<len)
  24. {
  25. l=r; //l hold the start character of the word
  26. while(r== len-2 || (r<len-1 && str[r+1] != ' ')) //Get the last character of the word in r
  27. r++;
  28.  
  29. reverseArr(str,l,r++);
  30.  
  31. while(r<len && str[r] == ' ') //Find the next character using r
  32. r++;
  33. }
  34. System.out.println(temp +" ----> " +new String(str));
  35. }
  36.  
  37.  
  38. /**
  39. * Reverse the character array between i and j (inclusive)
  40. */
  41. private static void reverseArr(char[] s,int i, int j) {
  42. int len=i+(j-i)/2; //look carefully this line, when i is not 0
  43. for(;i<=len;i++,j--)
  44. swap(s,i,j);
  45. }
  46.  
  47. /**
  48. * Swaps the ith and jth indices
  49. */
  50. private static void swap(char[] arr,int i, int j) {
  51. char temp = arr[i];
  52. arr[i] = arr[j];
  53. arr[j]=temp;
  54. }
  55.  
  56. public static void main(String[] args) {
  57. String s1 = " Coding Recipes is Super Cool ";
  58. String s2 = "I live to code";
  59. String s3 = "Recursion is Recursion";
  60. //reverseWords1(s.toCharArray());
  61. reverseWords(s1.toCharArray());
  62. reverseWords(s2.toCharArray());
  63. reverseWords(s3.toCharArray());
  64. reverseWords(" ".toCharArray());
  65. reverseWords(null);
  66. }
  67. }
  68.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
  Coding    Recipes is Super   Cool   ---->   Cool   Super is Recipes    Coding  
I live to code ----> code to live I
Recursion is Recursion ----> Recursion is Recursion
    ---->