Search Array for Longest String that is a Prefix of Search String

Viewed 250

I'm a new Swift developer. I'm using Swift 4.2 and Xcode 10.2.

I would like to search an array for a single result that has the most characters compared to my search string. To be more specific, I need the longest string from my array which is a prefix of the search string.

For example, if my array is:

let array = ["1", "13", "1410", "1649", "1670"]

and my search string is:

let searchString = "16493884777"

I would like the result to be "1649".

I can't find another SO question that has a swift solution.

1 Answers

You could just iterate over the prefix array from the end (assuming the prefix array is sorted) and return immediately if you hit a match since that prefix will be guaranteed to be the longest since another matching prefix of the same length cannot exist:

import Foundation

func longestMatchingPrefix(_ prefixArray: [String], _ searchString: String) -> String {
    for p in prefixArray.reversed() {
        if searchString.hasPrefix(p) {
           return p
        }
    }
    return "No matching prefix found"
}

print(longestMatchingPrefix(["1", "13", "1410", "1649", "1670"], "16493884777"))

Output:

1649
Related