Career Cup1-2

来源:互联网 发布:linux云计算培训 编辑:程序博客网 时间:2024/06/06 15:53

先找出字符串的长度,然后两头开始调换。速度很快,为O(n)


/**********************************************************


  Write code to reverse a C-Style String  (C-String means that “abcd” is represented as
five characters, including the null character )

  Note:

  This algorithm can be performed in O(n) time.

  Mod Time: 4.19, 2012

  Copyright: Ben Wu

  ***********************************************************/

#define STRING_MAX_LEN            10000

#include<stdio.h>
//#include<string.h>

void swap(char *apple, char *banana);

int main(void)
{
    char s[STRING_MAX_LEN];
    char ch;
    int StLen = 0, i, mid;
    FILE *fp;

    fp = fopen("String.txt", "r");

    while((ch = fgetc(fp)) != '\0')
    {
        s[StLen++] = ch;
    }
    s[StLen] = '\0';

    mid = StLen / 2;

    for(i = 0; i < mid; i++)
    {
        swap(s + i, s + StLen - 1 - i);
    }

    printf("%s", s);

    fclose(fp);

    return 0;
}

//swaps the 2 char
void swap(char *apple, char *banana)
{
    char temp;
    temp = *apple;
    *apple = *banana;
    *banana = temp;
}


原创粉丝点击