演算法小記·字串翻轉

只燈片箋發表於2018-11-05

寫一個函式,實現翻轉字串的功能,並考慮時間複雜度、空間複雜度,使其儘可能最小

1. 字串翻轉:請把”I am a student.”,翻轉成”.tneduts a ma I”;

吾來打個樣:

#include <stdio.h>
void reverseCharArray(char *str, char *begin, char *end) {
    while(begin < end) { //取地址,交換兩個字元
        char temp = *begin;
        *begin = *end;
        *end = temp;
        begin++;
        end--;
    }
}

char *reverse_str(char *str) {
    if(NULL == str) { //字串為空直接返回;
        return str;
    }
    char *begin;
    char *end;
    begin = end = str;
    
    while(*end != ` `) { //end指向字串的末尾;
        end++;
    }
    --end;  //取出最後一個`.`字元;
    
    //取字元陣列下標,進行交換;
    reverseCharArray(str, begin, end);
    
    return str; //返回結果;
}

int main(int argc, const char * argv[]) {
    char str[] = "I am a student.";
    printf("%s
", reverse_str(str));
    return 0;
}

2. 字串翻轉:請把 “I am a student.”,翻轉成 “I ma a .tneduts”;

吾來打個樣:

#include <stdio.h>
void reverseCharArray(char *str, char *begin, char *end) {
    while(begin < end) { //取地址,交換兩個字元
        char temp = *begin;
        *begin = *end;
        *end = temp;
        begin++;
        end--;
    }
}

char *reverseChar(char *str) {
    char *begin;
    char *end;
    begin = end = str;
    while (*end != ` `) {
        if (*end == ` `) {
            reverseCharArray(str, begin, end - 1);
            begin = end + 1;
        }
        else if (*(end + 1) == ` `) {  //當*(end + 1)取出的是字串陣列最後的` `的時候
            reverseCharArray(str, begin, end);
        }
        end++;
    }
    return str;
}

int main(int argc, const char * argv[]) {
    char str[] = "I am a student.";
    printf("%s
", reverseChar(str));
    return 0;
}

3. 字串翻轉:請把 “I am a student.”,翻轉為 “student. a am i”;

吾來打個樣:

#include <stdio.h>
void reverseCharArray(char *str, char *begin, char *end) {
    while(begin < end) { //取地址,交換兩個字元
        char temp = *begin;
        *begin = *end;
        *end = temp;
        begin++;
        end--;
    }
}

char *reverseChar(char *str) {
    char *begin;
    char *end;
    begin = end = str;
    while (*end != ` `) {
        if (*end == ` `) {
            reverseCharArray(str, begin, end - 1);
            begin = end + 1;
        }
        else if (*(end + 1) == ` `) {  //當*(end + 1)取出的是字串陣列最後的` `的時候
            reverseCharArray(str, begin, end);
        }
        end++;
    }
    return str;
}

int main(int argc, const char * argv[]) {
    char str[] = "I am a student.";
    char *begin;
    char *end;
    begin = end = str;

    while(*end != ` `) { //end指向字串的末尾;
        end++;
    }
    --end;  //取出最後一個`.`字元;
    reverseCharArray(str, begin, end);
    printf("%s
", reverseChar(str));
    return 0;
}


相關文章