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

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

    @Daren Thomas

    Implementation of your algorithm (O(N) in time, O(1) in space) in D (Digital Mars):

    #!/usr/bin/dmd -run
    /**
     * to compile & run:
     * $ dmd -run reverse_words.d
     * to optimize:
     * $ dmd -O -inline -release reverse_words.d
     */
    import std.algorithm: reverse;
    import std.stdio: writeln;
    import std.string: find;
    
    void reverse_words(char[] str) {
      // reverse whole string
      reverse(str);
    
      // reverse each word
      for (auto i = 0; (i = find(str, " ")) != -1; str = str[i + 1..length])
        reverse(str[0..i]);
    
      // reverse last word
      reverse(str);
    }
    
    void main() {
      char[] str = cast(char[])("this is a string");
      writeln(str);
      reverse_words(str);
      writeln(str);
    }
    

    Output:

    this is a string
    string a is this

提交回复
热议问题