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

前端 未结 21 1935
[愿得一人]
[愿得一人] 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 04:56

    A solution in C/C++:

    void swap(char* str, int i, int j){
        char t = str[i];
        str[i] = str[j];
        str[j] = t;
    }
    
    void reverse_string(char* str, int length){
        for(int i=0; i

    This should be O(n) in time and O(1) in space.

    Edit: Cleaned it up a bit.

    The first pass over the string is obviously O(n/2) = O(n). The second pass is O(n + combined length of all words / 2) = O(n + n/2) = O(n), which makes this an O(n) algorithm.

提交回复
热议问题