Skip to content

Instantly share code, notes, and snippets.

@mteece
Last active March 9, 2021 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mteece/abd4c5c9c847f9fe4269a3add92c2c62 to your computer and use it in GitHub Desktop.
Save mteece/abd4c5c9c847f9fe4269a3add92c2c62 to your computer and use it in GitHub Desktop.
Design a function that takes two string parameters. The function should return the longest substring that fully matches the provided pattern. Assume that the input and pattern characters are alphabetic.
import UIKit
import Foundation
/** Design a function that takes two string parameters:
input
pattern
The function should return the longest substring that fully matches
the provided pattern. Assume that the input and pattern characters are
alphabetic.
find_match("abcdcef", "cd") -> "cd"
Function prototype:
string find_match(string input, string pattern);
**/
func find_match(input:String, pattern:String) -> String {
var endOffset = pattern.count
var result = ""
while(endOffset >= 1) {
var match = String(pattern.prefix(upTo: pattern.index(pattern.startIndex, offsetBy:endOffset)))
if(input.contains(match)) {
result = match
break
} else {
match = String(pattern.suffix(pattern.count - endOffset + 1))
if(input.contains(match)){
result = match
break
}
}
endOffset-=1
}
return result
}
let resultOne = find_match(input: "catwithacap", pattern: "cat")
let resultTwo = find_match(input: "abcdefg", pattern: "cd")
let resultThree = find_match(input: "doginthedogecoin", pattern: "dog")
let resultFour = find_match(input: "CodingAndInterviews", pattern: "CodingQuiz")
print(resultOne, resultTwo, resultThree, resultFour) // cat cd dog Coding
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment