题目:字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。
代码如下:
package demo;
/**
* 左旋转字符串
*
* @author xiangdonglee
*
*/
public class Test42_2 {
/**
* 将data中start到end之间的字符翻转
*
* @param data
* @param start
* @param end
*/
public static void reverse(char[] data, int start, int end) {
if (data == null || data.length < 1 || start < 0 || end > data.length || start > end) {
return;
}
while (start < end) {
char tmp = data[start];
data[start] = data[end];
data[end] = tmp;
start++;
end--;
}
}
public static char[] leftRotateString(char[] data, int n) {
if (data == null || data.length < 1 || n < 0 || n > data.length) {
return data;
}
reverse(data, 0, data.length - 1);
reverse(data, 0, data.length - n - 1);
reverse(data, data.length - n, data.length - 1);
return data;
}
public static void main(String[] args) {
test2();
}
private static void test2() {
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 2)));
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 1)));
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 6)));
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 7)));
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 0)));
}
}