【算法】字符串问题——翻转字符串

时间:2022-04-16 11:17:34

 

    /**
     * 翻转字符串'
     * 给定一个字符类型的数组chas,请在单词间作逆序调整。只要做到单词顺序逆序即可。
     * 例如,如果看成字符串"dog loves pig",则调整为"pig loves dog"
     * 过程:先整体逆序,在局部单词逆序
     */
    public static void rotateWord(char[] chas) {

        if (chas == null || chas.length <= 0) {
            return;
        }
        reverse(chas, 0, chas.length - 1);
        int l = -1;
        int r = -1;
        for (int i = 0; i < chas.length; i++) {
            if (chas[i] != ' ') {
                l = i == 0 || chas[i - 1] == ' ' ? i : l;
                r = i == chas.length - 1 || chas[i + 1] == ' ' ? i : r;
            }
            if (l != -1 && r != -1) {
                reverse(chas, l, r);
                l = -1;
                r = -1;
            }
        }
    }

    public static void reverse(char[] chas, int start, int end) {
        char tmp;
        while (start != end) {
            tmp = chas[start];
            chas[start] = chas[end];
            chas[end] = tmp;
            start++;
            end--;
        }
    }
 1 /**
 2      * 翻转字符串'
 3      * 给定一个字符类型的数组chas,和一个整数size,请把大小为size的左半区整体移到右半区,右半区间整体移到左半区间
 4      * 例如,"ABCDE",size=3,调整为"DEABC"
 5      * 过程:先逆序前部分,在逆序后部分,最后逆序整体
 6      */
 7     public static void rotate1(char[] chas, int size) {
 8         if (chas == null || size <= 0 || size >= chas.length) {
 9             return;
10         }
11         reverse(chas, 0, size - 1);
12         reverse(chas, size, chas.length - 1);
13         reverse(chas, 0, chas.length - 1);
14     }
15     
16     public static void reverse(char[] chas, int start, int end) {
17         char tmp;
18         while (start != end) {
19             tmp = chas[start];
20             chas[start] = chas[end];
21             chas[end] = tmp;
22             start++;
23             end--;
24         }
25     }