Advertisement
Guest User

Untitled

a guest
Jul 31st, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 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.  
  15.     for (int i = 0; i < m.length/2; i++) {
  16.  
  17.       if (m.length % 2 != 0 && i == m.length/2) {
  18.         // don't switch the middle element of an odd array.
  19.         break;
  20.       }
  21.  
  22.       char tmp = m[i];
  23.       m[i] = m[m.length-1-i];
  24.       m[m.length-1-i] = tmp;
  25.     }
  26.  
  27.     for (int i = 0; i < m.length; i++) {
  28.       System.out.print(m[i] + " ");
  29.     }
  30.     System.out.println();
  31.  
  32.  
  33.     int start = 0;
  34.     for (int i = 0; i < m.length; i++) {
  35.       if (m[i] == ' ') {
  36.         reverse(start, i, m);
  37.         start = i+1;
  38.       }
  39.     }
  40.  
  41.     reverse(start, m.length, m);
  42.  
  43.     for (int i = 0; i < m.length; i++) {
  44.       System.out.print(m[i] + " ");
  45.     }
  46.     System.out.println();
  47.   }
  48.  
  49.   private static void reverse(int start, int end, char[] m) {
  50.     // end exclusive.
  51.     int size = end-start;
  52.  
  53.     for (int i = 0; i < size/2; i++) {
  54.       if (size % 2 != 0 && i == size/2) {
  55.         break; // don't swap middle element in odd.
  56.       }
  57.  
  58.       char tmp = m[start+i];
  59.       m[start+i] = m[end-1-i];
  60.       m[end-1-i] = tmp;
  61.     }
  62.   }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement