算法小记 · 字符串翻转

2018-11-05  本文已影响57人  寒山半秋

写一个函数,实现翻转字符串的功能,并考虑时间复杂度、空间复杂度,使其尽可能最小

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 != '\0') { //end指向字符串的末尾;
        end++;
    }
    --end;  //取出最后一个'.'字符;
    
    //取字符数组下标,进行交换;
    reverseCharArray(str, begin, end);
    
    return str; //返回结果;
}

int main(int argc, const char * argv[]) {
    char str[] = "I am a student.";
    printf("%s\n", 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 != '\0') {
        if (*end == ' ') {
            reverseCharArray(str, begin, end - 1);
            begin = end + 1;
        }
        else if (*(end + 1) == '\0') {  //当*(end + 1)取出的是字符串数组最后的'\0'的时候
            reverseCharArray(str, begin, end);
        }
        end++;
    }
    return str;
}

int main(int argc, const char * argv[]) {
    char str[] = "I am a student.";
    printf("%s\n", 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 != '\0') {
        if (*end == ' ') {
            reverseCharArray(str, begin, end - 1);
            begin = end + 1;
        }
        else if (*(end + 1) == '\0') {  //当*(end + 1)取出的是字符串数组最后的'\0'的时候
            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 != '\0') { //end指向字符串的末尾;
        end++;
    }
    --end;  //取出最后一个'.'字符;
    reverseCharArray(str, begin, end);
    printf("%s\n", reverseChar(str));
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读