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

前端 未结 21 1909
[愿得一人]
[愿得一人] 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条回答
  •  Happy的楠姐
    2020-11-28 04:41

    You would use what is known as an iterative recursive function, which is O(N) in time as it takes N (N being the number of words) iterations to complete and O(1) in space as each iteration holds its own state within the function arguments.

    (define (reverse sentence-to-reverse)
      (reverse-iter (sentence-to-reverse ""))
    
    (define (reverse-iter(sentence, reverse-sentence)
      (if (= 0 string-length sentence)
        reverse-sentence
        ( reverse-iter( remove-first-word(sentence), add-first-word(sentence, reverse-sentence)))
    

    Note: I have written this in scheme which I am a complete novice, so apologies for lack of correct string manipulation.

    remove-first-word finds the first word boundary of sentence, then takes that section of characters (including space and punctuation) and removes it and returns new sentence

    add-first-word finds the first word boundary of sentence, then takes that section of characters (including space and punctuation) and adds it to reverse-sentence and returns new reverse-sentence contents.

提交回复
热议问题