Created
March 14, 2014 05:02
-
-
Save rayjcwu/9542367 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class StringRotate { | |
| int count; | |
| public static void main(String[] argv) { | |
| StringRotate sr = new StringRotate(); | |
| System.out.println(sr.wordSwap("0123456789", 1)); | |
| System.out.println(sr.wordSwap("012345", 2)); | |
| } | |
| public String wordSwap(String string, int firstWordLength) { | |
| count = 0; | |
| char[] str = string.toCharArray(); | |
| wordSwap(str, 0, str.length, firstWordLength); | |
| System.out.println(count + " swaps"); | |
| return new String(str); | |
| } | |
| // [start, end), | |
| // first word length: M | |
| // second word length: N | |
| public void wordSwap(char[] str, int start, int end, int M) { | |
| if (end <= start) { | |
| return; | |
| } | |
| final int L = end - start; | |
| final int N = L - M; | |
| final int minMN = Math.min(M, N); | |
| for (int i = 0; i < minMN; ++i) { | |
| swap(str, start + i, end - minMN + i); | |
| } | |
| // only need to recur if M != N | |
| if (M > N) { | |
| wordSwap(str, start + N, end, M - N); | |
| } else if (M < N) { | |
| wordSwap(str, start, end - M, M); | |
| } | |
| } | |
| private void swap(char[] A, int i, int j) { | |
| count++; | |
| char t = A[i]; | |
| A[i] = A[j]; | |
| A[j] = t; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment