Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Challenge:
- Your challenge today is to write a function longestConsecutive() that,
- given and array of strings and an integer n, returns the longest string
- consisting of n consecutive strings from the array. If there is more than
- one longest string, return the first.
- i.e. Which n consecutive strings in the array are the longest?
- To build your algorithm, consider k the length of the array of strings.
- If k = 0, or n > k, or n <= 0 then return an empty string.
- Example:
- longestConsecutive(["zone", "abigail", "theta", "form", "libe", "zas"], 2) // returns "abigailtheta"
- longestConsecutive(["zone", "abigail"], 3) // returns ""
- */
- func longestConsecutive(_ arr: [String], _ n: Int) -> String{
- if arr.isEmpty || n > arr.count || n <= 0 {
- return ""
- }
- var longestStringIndex = 0
- for (index, str) in arr.enumerated() {
- if str.count > arr[longestStringIndex].count {
- longestStringIndex = index
- }
- }
- var consecutiveString = ""
- for i in longestStringIndex...n {
- consecutiveString += arr[i]
- }
- return consecutiveString
- }
- //let lc = longestConsecutive(["zone", "abigail"], 3)
- let lc = longestConsecutive(["zone", "abigail", "theta", "form", "libe", "zas"], 2) // returns "abigailtheta"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement