Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 21, 2021 08:09
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 vrat28/624f8ead35861f13ba45260025070f48 to your computer and use it in GitHub Desktop.
Save vrat28/624f8ead35861f13ba45260025070f48 to your computer and use it in GitHub Desktop.
Find and Replace
class Solution {
func findAndReplacePattern(_ words: [String], _ pattern: String) -> [String] {
var output = [String]()
for word in words {
if isMatch(word,pattern) {
output.append(word)
}
}
return output
}
func isMatch(_ word:String, _ pattern:String) -> Bool {
var mapW = [Character:Character]()
var mapP = [Character:Character]()
for (w,p) in zip(word,pattern){
if mapW[w] == nil{
mapW[w] = p
}
if mapP[p] == nil{
mapP[p] = w
}
if mapW[w] != p || mapP[p] != w {
return false
}
}
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment