編寫⼀個函數,把⼀個 CHAR 組成的字符串循環右移 N 位。例如:原來 是”ABCDEFGHI”,如果 N = 2,移位後應該是”HIABCDEFG”
三次翻轉的思想,下午寫xx公司筆試題的時候寫到了。
注意下標即可。
public class Swap {
public void swap(char[] arr, int begin, int end){
while(begin < end){
char temp = arr[begin];
arr[begin] = arr[end];
arr[end] = temp;
begin++;
end--;
}
}
public String swaptheWords(String str, int n){
char[] chars = str.toCharArray();
swap(chars, 0, chars.length - 1);
swap(chars, 0, n-1);
swap(chars, n, chars.length - 1);
return new String(chars);
}
public static void main(String[] args) {
String str = "ABCDEFGHI";
int n = 2;
System.out.println(new Swap().swaptheWords(str,n));
}
}