美文网首页
【剑指Offer 42】左旋转字符串

【剑指Offer 42】左旋转字符串

作者: 3e1094b2ef7b | 来源:发表于2017-07-22 22:25 被阅读5次

题目:字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。

代码如下:

package demo;

/**
 * 左旋转字符串
 * 
 * @author xiangdonglee
 *
 */
public class Test42_2 {
    /**
     * 将data中start到end之间的字符翻转
     * 
     * @param data
     * @param start
     * @param end
     */
    public static void reverse(char[] data, int start, int end) {
        if (data == null || data.length < 1 || start < 0 || end > data.length || start > end) {
            return;
        }
        while (start < end) {
            char tmp = data[start];
            data[start] = data[end];
            data[end] = tmp;
            start++;
            end--;
        }
    }

    public static char[] leftRotateString(char[] data, int n) {
        if (data == null || data.length < 1 || n < 0 || n > data.length) {
            return data;
        }
        reverse(data, 0, data.length - 1);
        reverse(data, 0, data.length - n - 1);
        reverse(data, data.length - n, data.length - 1);
        return data;
    }

    public static void main(String[] args) {
        test2();
    }

    private static void test2() {
        System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 2)));
        System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 1)));
        System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 6)));
        System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 7)));
        System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 0)));
    }
}
运行结果

来源:http://blog.csdn.net/derrantcm/article/details/46784471

相关文章

网友评论

      本文标题:【剑指Offer 42】左旋转字符串

      本文链接:https://www.haomeiwen.com/subject/hrcpkxtx.html