大家好,欢迎来到IT知识分享网。
旋转string
Given a string and an offset, rotate string by offset. (rotate from left to right)
Given “abcdefg”
for offset=0, return “abcdefg”
for offset=1, return “gabcdef”
for offset=2, return “fgabcde”
for offset=3, return “efgabcd”
Solution:
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)实现数组拷贝。
三步翻转法。一定是段内有序。
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/16224.html