Reverse words in a sentence - Swift

后端 未结 5 840
不知归路
不知归路 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:19

    Building on the OPs answer, if you wanted to follow English capitalization rules on the output:

    var str = "Hello playground"
    
    let result = str.split(separator: " ").enumerated().map {
        let reversed = String($0.1.reversed())
        return $0.0 == 0 ? reversed.capitalized : reversed.lowercased()
        }
        .joined(separator: " ")
    print("Rerversing letters in each word = \"" + result + "\"") // Olleh dnuorgyalp
    

    Also note that multiple spaces would mess this up, as would commas, periods, and other word/sentence delimiters.

    0 讨论(0)
  • 2021-01-29 16:23

    Working code!

     import UIKit
    
     var str = "Hello playground"
    
     let result = str.split(separator: " ").map { String($0.reversed())}.joined(separator: " ")
     print(result) // olleH dnuorgyalp
    
    0 讨论(0)
  • 2021-01-29 16:23
    let result = String(str.reversed())
        .components(separatedBy: .whitespaces)
        .reversed()
        .joined(separator: " ")
    
    0 讨论(0)
  • 2021-01-29 16:36

    You can use String method enumerateSubstrings using .byWords options and replace the subrange of each word with the substring reversed. Note that this way the punctuation will remain in place:


    import Foundation
    

    Mutating approach:

    var str = "Hello, playground!!!"
    
    str.enumerateSubstrings(in: str.startIndex..., options: .byWords) { _, range, _, _ in
        str.replaceSubrange(range, with: str[range].reversed())
    }
    print(str)  // "olleH, dnuorgyalp!!!"
    

    Non mutating:

    let str = "Hello, playground!!!"
    var result = ""
    str.enumerateSubstrings(in: str.startIndex..., options: .byWords) { string, range, enclosingRange, _ in
        result.append(contentsOf: string!.reversed())
        result.append(contentsOf: str[range.upperBound..<enclosingRange.upperBound])
    }
    print(result)  // "olleH, dnuorgyalp!!!"
    
    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题