Efficiently reverse the order of the words (not characters) in an array of characters

前端 未结 21 1958
[愿得一人]
[愿得一人] 2020-11-28 04:40

Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

Example input and

21条回答
  •  没有蜡笔的小新
    2020-11-28 05:07

    In C: (C99)

    #include 
    #include 
    
    void reverseString(char* string, int length)
    {
        char swap;
        for (int i = 0; i < length/2; i++)
        {
            swap = string[length - 1 - i];
            string[length - 1 - i] = string[i];
            string[i] = swap;
        }   
    }
    
    int main (int argc, const char * argv[]) {
        char teststring[] = "Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.";
        printf("%s\n", teststring);
        int length = strlen(teststring);
        reverseString(teststring, length);
        int i = 0;
        while (i < length)
        {
            int wordlength = strspn(teststring + i, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
            reverseString(teststring + i, wordlength);
            i += wordlength + 1;
        }
        printf("%s\n", teststring);
        return 0;
    }
    

    This gives output:

    Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

    .it in )characters not( words the of order the reverse to algorithm efficient an give ,words of sentence a form which characters of array an Given

    This takes at most 4N time, with small constant space. Unfortunately, It doesn't handle punctuation or case gracefully.

提交回复
热议问题