美文网首页
【算法学习】C Reverse String

【算法学习】C Reverse String

作者: Jiubao | 来源:发表于2017-01-25 10:29 被阅读37次

题目 - 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

      本文链接:https://www.haomeiwen.com/subject/umutittx.html