給定一個字符串,要求把字符串前面的若干個字符移動到字符串的尾部
public class StringReverse {
private void reverseString(char[] str, int start, int end) {
while (start < end) {
char c = str[start];
str[start++] = str[end];
str[end--] = c;
}
}
/*
假設(shè)字符串由XY兩部分組成,定義X翻轉(zhuǎn)后為X^T奇徒,Y翻轉(zhuǎn)為Y^T叶沛,那么可得(X^TY^T)^T=YX字符串成功旋轉(zhuǎn)
*/
public void rotateString(char[] str, int n, int m) {
m = m % n;
//翻轉(zhuǎn)前m個
reverseString(str, 0, m - 1);
//翻轉(zhuǎn)后m-n個
reverseString(str, m, n - 1);
//整體翻轉(zhuǎn)
reverseString(str, 0, n - 1);
}
public static void main(String[] args) {
char[] str = "abcde".toCharArray();
StringReverse sReverse = new StringReverse();
sReverse.rotateString(str, 5, 2);
System.out.println(str);
}
}