Advertisement
Guest User

Untitled

a guest
Jul 31st, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. /**
  2.  * Created by hcardena on 7/30/16.
  3.  */
  4. public class reverseWord {
  5.  
  6.   public static void main(String[] args) {
  7.     String message = "find you will pain only go you recordings security the into if";
  8.     //               "if into the security recordings you go only pain will you find"
  9.     char[] m = message.toCharArray();
  10.  
  11.     // a b c. length = 3/2 = 1
  12.     // a b. length = 2/2 = 1
  13.  
  14.     reverse(0, m.length, m);
  15.  
  16.     int start = 0;
  17.     for (int i = 0; i < m.length; i++) {
  18.       if (m[i] == ' ') {
  19.         reverse(start, i, m);
  20.         start = i+1;
  21.       }
  22.     }
  23.  
  24.     reverse(start, m.length, m);
  25.  
  26.     for (int i = 0; i < m.length; i++) {
  27.       System.out.print(m[i]);
  28.     }
  29.     System.out.println();
  30.   }
  31.  
  32.   private static void reverse(int start, int end, char[] m) {
  33.     // end exclusive.
  34.     int size = end-start;
  35.  
  36.     for (int i = 0; i < size/2; i++) {
  37.       if (size % 2 != 0 && i == size/2) {
  38.         break; // don't swap middle element in odd.
  39.       }
  40.  
  41.       char tmp = m[start+i];
  42.       m[start+i] = m[end-1-i];
  43.       m[end-1-i] = tmp;
  44.     }
  45.   }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement