Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by hcardena on 7/30/16.
- */
- public class reverseWord {
- public static void main(String[] args) {
- String message = "find you will pain only go you recordings security the into if";
- // "if into the security recordings you go only pain will you find"
- char[] m = message.toCharArray();
- // a b c. length = 3/2 = 1
- // a b. length = 2/2 = 1
- reverse(0, m.length, m);
- int start = 0;
- for (int i = 0; i < m.length; i++) {
- if (m[i] == ' ') {
- reverse(start, i, m);
- start = i+1;
- }
- }
- reverse(start, m.length, m);
- for (int i = 0; i < m.length; i++) {
- System.out.print(m[i]);
- }
- System.out.println();
- }
- private static void reverse(int start, int end, char[] m) {
- // end exclusive.
- int size = end-start;
- for (int i = 0; i < size/2; i++) {
- if (size % 2 != 0 && i == size/2) {
- break; // don't swap middle element in odd.
- }
- char tmp = m[start+i];
- m[start+i] = m[end-1-i];
- m[end-1-i] = tmp;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement