字符串旋转

题目:给定字符串,将字符串前几位移动到字符串尾部。
样例:“abcdef” ,将前三位移动到字符串尾部,则结果为“defabc”
解法1:蛮力移位

public class RevertString {

    private static String shiftOne(String str) {
        char[] chars = str.toCharArray();
        char head = chars[0];
        for (int i = 1; i < chars.length; i++) {
            chars[i - 1] = chars[i];
        }
        chars[chars.length - 1] = head;
        return String.valueOf(chars);
    }

    private static String revert(String str,int size) {
        for (int i = 0; i < size; i++) {
            str = shiftOne(str);
        }
        return str;
    }

    public static void main(String[] args) {
        System.out.println(revert("abcdef",3));
    }
}

该解法时间复杂度O(mn)

解法2:三步反转法

private static String revertString(String str, int from, int to) {
        char[] chars = str.toCharArray();
        while (from < to) {
            char head = chars[from];
            chars[from++] = chars[to];
            chars[to--] = head;
        }
        return String.valueOf(chars);
    }

    private static String revert(String str, int size) {
        str = revertString(str, 0, size - 1);
        str = revertString(str, size, str.length() - 1);
        str = revertString(str, 0, str.length() - 1);
        return str;
    }

    public static void main(String[] args) {
        System.out.println(revert("abcdef", 3));
    }

该解法时间复杂度O(n)

拓展:单词反转,例如将"I work for money."反转为"money. for work I"

    private static String revert(String str, int from, int to) {
        char[] chars = str.toCharArray();
        while (from < to) {
            char head = chars[from];
            chars[from++] = chars[to];
            chars[to--] = head;
        }
        return String.valueOf(chars);
    }

    public static void main(String[] args) {
        String str = "I work for money.";
        str = revert(str, 0, str.length() - 1);
        String key = " ";
        int start = 0;
        int blankIndex = str.indexOf(key, start);
        while (blankIndex != -1) {
            str = revert(str, start, blankIndex - 1);
            start = blankIndex + 1;
            blankIndex = str.indexOf(key, start);
        }
        System.out.println(str);
    }

你可能感兴趣的:(字符串旋转)