1. 程式人生 > >字串翻轉 要求空間複雜度為O(1)

字串翻轉 要求空間複雜度為O(1)

1.特例:全部翻轉

比如:goodboy 翻轉以後為:yobdoog

思路:就是取得字串的長度length,然後用一個臨時變數做中轉兩兩交換,就是0和最後一個交換,1和倒數第二個交換,依次類推

2.通例:把尾部的n個字元移到字串的頭部

思路:也是用到了兩兩交換的方法

比如說:要把尾部的3個字元移到頭部,先把length-3-1=3,就是索引從0到3的子字串翻轉;然後再把索引是3+1=4到length-1=6的子字串翻轉,最後整體翻轉即可

上程式碼

private static String reserve(String test, int index) {
        int length = test.length();
        
int begine = (length - index - 1)%length;char[] chars = test.toCharArray(); turnOver(chars,0,begine); turnOver(chars,begine+1,length-1); turnOver(chars,0,length-1); return new String(chars); } private static void turnOver(char[] chars, int begine, int to) { if(begine < to){
for (; begine < to; begine++,to--) { swap(chars,begine,to); } } } private static void swap(char[] chars, int begine, int to) { char temp = chars[begine]; chars[begine] = chars[to]; chars[to] = temp; }

3.根據某個特定字元進行翻轉

比如goodbye 根據d翻轉  結果為:yebgood

思路:特定字元左邊的子字串翻轉,右邊的子字串也翻轉,最後整體翻轉

上程式碼:

//根據某一個特定的字元進行翻轉
    private static String reserve(String test, char index) {
        
        char[] chars = test.toCharArray();
        int from = 0,to = 0;
        for (int i = 0; i < chars.length; i++) {
            char temp = chars[i];
            if(temp == index){
                to = i-1;
                turnOver(chars,from,to);
                from = i+1;
            }
        }
        
        if(to < chars.length - 1){
            turnOver(chars, from, chars.length-1);
        }
        
        turnOver(chars,0,chars.length-1);
        return new String(chars);
    }

注意這個方法也可以 吧  I am a student.按空格進行翻轉