【算法学习】C Reverse String

题目 - leetcode

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

C 解题

char* reverseString(char* s) {
    int i = 0;
    while (s[i] != '\0') {
        i++;
    }

    int length = i;
    char *temp = (char *) malloc ((length + 1) * sizeof(char));
    
    for (int j = length; j >= 0; j--) {
        temp[length-j] = s[j-1];
    }
    
    return temp;
}

纠错

首先是在计算字符串长度的时候,结尾尝试了 “EOF”,但是这样初始化的字符串,其结尾应该是“\0”,导致结尾判断失败。

其次是在反向复制的时候,把结尾的“\0”复制到了第一个,导致复制的字符串直接就结束了。

你可能感兴趣的:(【算法学习】C Reverse String)