字符串循环右移-三次翻转思想-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));
    }
}

 

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