Last active
March 9, 2021 20:15
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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