旋转string
Given a string and an offset, rotate string by offset. (rotate from left to right)
Example
Solution:
Given "abcdefg"
for offset=0, return "abcdefg"
for offset=1, return "gabcdef"
for offset=2, return "fgabcde"
for offset=3, return "efgabcd"
public char[] rotateString(char[] A, int offset) {
if (A == null) {
return null;
}
char[] result = new char[A.length];
if (A.length == 0) {
return result;
}
offset = offset % A.length;
int i;
int j;
for (i = 0, j = A.length - offset; i < offset; i++, j++) {
result[i] = A[j];
}
for (j = 0; j < A.length - offset; i++, j++) {
result[i] = A[j];
}
return result;
}
public char[] rotateString(char[] A, int offset) {
if (A == null) {
return null;
}
char[] result = new char[A.length];
if (A.length == 0) {
return result;
}
offset = offset % A.length;
System.arraycopy(A, A.length - offset, result, 0, offset);
System.arraycopy(A, 0, result, offset, A.length - offset);
return result;
}
public char[] rotateString(char[] A, int offset) {
if(A == null|| A.length <= 1) {
return A;
}
offset = offset % A.length;
if(offset <= 0) {
return A;
}
//0123456
//abcdefg
reverse(A, A.length - offset, A.length - 1);
reverse(A, 0, A.length - offset - 1);
reverse(A, 0, A.length - 1);
return A;
}
private void reverse(char[] A, int start, int end) {
for(int i = start, j = end; i < j; i++,j--) {
char temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
思路:
双index用起来方便。一段是0到A.length - offset - 1, 一段是A.length - offset到A.length - 1. 先把后一段拷贝,在把前一段拷贝。
使用System.arraycopy(src, SrcStart, dest, DestStart, len)实现数组拷贝。
三步翻转法。一定是段内有序。