Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. /*
  2. Challenge:
  3. Your challenge today is to write a function longestConsecutive() that,
  4. given and array of strings and an integer n, returns the longest string
  5. consisting of n consecutive strings from the array. If there is more than
  6. one longest string, return the first.
  7.  
  8. i.e. Which n consecutive strings in the array are the longest?
  9.  
  10. To build your algorithm, consider k the length of the array of strings.
  11. If k = 0, or n > k, or n <= 0 then return an empty string.
  12.  
  13. Example:
  14. longestConsecutive(["zone", "abigail", "theta", "form", "libe", "zas"], 2) // returns "abigailtheta"
  15. longestConsecutive(["zone", "abigail"], 3) // returns ""
  16.  
  17. */
  18.  
  19.  
  20.  
  21.  
  22. func longestConsecutive(_ arr: [String], _ n: Int) -> String{
  23. if arr.isEmpty || n > arr.count || n <= 0 {
  24. return ""
  25. }
  26.  
  27. var longestStringIndex = 0
  28.  
  29. for (index, str) in arr.enumerated() {
  30. if str.count > arr[longestStringIndex].count {
  31. longestStringIndex = index
  32. }
  33. }
  34.  
  35. var consecutiveString = ""
  36.  
  37. for i in longestStringIndex...n {
  38. consecutiveString += arr[i]
  39. }
  40.  
  41. return consecutiveString
  42. }
  43. //let lc = longestConsecutive(["zone", "abigail"], 3)
  44. let lc = longestConsecutive(["zone", "abigail", "theta", "form", "libe", "zas"], 2) // returns "abigailtheta"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement