左旋字符串

来源:互联网 发布:天下3男脸数据 编辑:程序博客网 时间:2024/06/02 08:10
/** * 定义字符串左旋转操作:把字符串前面的若干个字符移动到字符串尾部,如把字符串"abcdef"左旋转 2位得到字符串 "cdefab"。 * 请实现字符串左旋转的函数,要求对长度为 n 的字符串操作的时间复杂度为 O(n),空间复杂度为 O(1)。 * @author Administrator * */public class LeftShiftString {    /**     * 翻转字符串     * @param str     * @param begin     * @param end     */    public static void reverse(char[] str, int begin, int end) {        if (str == null || str.length == 0 || begin < 0 || end >= str.length) {            return;        }        char temp;        while (begin < end) {            temp = str[begin];            str[begin] = str[end];            str[end] = temp;            ++begin;            --end;        }    }        /**     * 通过三次翻转来实现左旋     * @param str     * @param n     */    public static void leftShift(char[] str, int n) {        if (str == null || str.length == 0 || n <= 0) {            return;        }        n = n % str.length;        reverse(str, 0, n - 1);        reverse(str, n, str.length - 1);        reverse(str, 0, str.length - 1);            }        public static void main(String[] args) {        char[] str = {'a', 'b', 'c', 'd', 'e', 'f'};        leftShift(str, 2);        System.out.println(str);    }}

0 0