TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.