左右旋转字符串/数组

题目描述

汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
 
// 右旋转,先整体reverse,然后0到n,然后n到结尾
public void rotateRight(int[] num, int n) {
if (num == null || num.length == 0 || n < 0) {
return;
}
reverse(num, 0, num.length - 1);
reverse(num, 0, n - 1);
reverse(num, n, num.length - 1);
}

private void reverse(int[] num, int low, int high) {
while (low < high) {
int temp = num[low];
num[low] = num[high];
num[high] = temp;
low++;
high--;
}
}

// 左旋转,和右旋转逻辑一致,左旋转n即右旋转length-n,
public void rotateLeft(int[] num, int n) {
if (num == null || num.length == 0 || n < 0) {
return;
}
int rotate = num.length - n;
reverse(num, 0, num.length - 1);
reverse(num, 0, rotate - 1);
reverse(num, rotate, num.length - 1);
}

private void reverse(int[] num, int low, int high) {
while (low < high) {
int temp = num[low];
num[low] = num[high];
num[high] = temp;
low++;
high--;
}
}
posted @ 2018-10-11 18:23  MarkLeeBYR  阅读(123)  评论(0)    收藏  举报