UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Swift Coding Challenges: Find longest prefix

Forums > Books

In the book Swift Coding Challenges, Chapter 12: Find longest prefix, the challenge is to "Write a function that accepts a string of words with a similar prefix, separated by spaces, and returns the longest substring that prefixes all words.

The book provided the following solution:

func challenge12(input: String) -> String {
    let parts = input.components(separatedBy: " ")
    guard let first = parts.first else { return "" }

    var currentPrefix = ""
    var bestPrefix = ""

    for letter in first {
    currentPrefix.append(letter)

        for word in parts {
            if !word.hasPrefix(currentPrefix) {
                return bestPrefix
            }
        }

        bestPrefix = currentPrefix
    }

    return bestPrefix
}

I chose another approach. Could you offer critique on my approach compared with the given solution? Thanks !

func challenge12(input: String) -> String {

    var words = input.components(separatedBy: " ")
    words.sort(){$0.count < $1.count}
    var prefix = words[0]
    for i in 1..<words.count {
        prefix = prefix.commonPrefix(with: words[i])
        guard prefix.count > 0 else {return ""}
    }
    return prefix
}
print(challenge12(input: "swift switch swill swim"))
print(challenge12(input: "flip flap flop"))
assert(challenge12(input: "swift switch swill swim") == "swi", "failed test")
assert(challenge12(input: "flip flap flop") == "fl", "failed test")

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.