Created
May 21, 2021 08:09
-
-
Save vrat28/624f8ead35861f13ba45260025070f48 to your computer and use it in GitHub Desktop.
Find and Replace
This file contains 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
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