Reverse words in a sentence - Swift

后端 未结 5 887
不知归路
不知归路 2021-01-29 15:43

How to perform reversing of all words in a sentence.

Example

let str = \"Hello playground\"

Result should be like \"olleH dnuorg

5条回答
  •  梦如初夏
    2021-01-29 16:43

    Here's the typical functional programming approach (also posted by @Saranjith)

    let result = str
        .components(separatedBy: " ")
        .map { $0.reversed() }
        .joined()
    

    Complexity

    First of all lets define

    • n: the number of characters in the input string
    • k: the number of words in the input string (of course k<=n)

    ⏳ Time complexity

    Now lets look at the time complexity of each piece of our code

    .components(separatedBy: " ")

    This instructions need to go through the entire string so O(n)

    .map { $0.reversed() }

    Here each word is reversed. So if we have k words we have a time complexity of

    O(m0) + O(m1) + ... + O(mk-1)
    

    where mi is the length of the i-th word. However the sum of the length of all the words is <= n so we can say that

    O(m0) + O(m1) + ... + O(mk-1) <= O(n)
    

    .joined()

    Finally we have k words which need to be joined togheter. This can be done in O(k) that, again, is <= O(n).

    Wrap up

    let result = str
        .components(separatedBy: " ") // O(n)
        .map { $0.reversed() } // O(m0) + O(m1) + ... + O(mk-1) <= O(n)
        .joined() // O(k) <= O(n)
    

    Time complexity = O(n) + O(n) + O(n) = O(n)

提交回复
热议问题