字符串循環右移-三次翻轉思想-Java實現

編寫⼀個函數,把⼀個 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));
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章