Created
July 30, 2022 00:12
-
-
Save germanescobar/6c5ff2651567293b0ad97b8311af98af to your computer and use it in GitHub Desktop.
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
var findAndReplacePattern = function(words, pattern) { | |
const result = [] | |
for (let i=0; i < words.length; i++) { | |
const word = words[i] | |
if (matchPattern(word, pattern)){ | |
result.push(word) | |
} | |
} | |
return result | |
}; | |
function matchPattern(word, pattern) { | |
const charMapping = {} | |
const charSet = new Set() | |
for (let i=0; i < pattern.length; i++) { | |
const charPattern = pattern[i] | |
const charWord = word[i] | |
const found = charMapping[charPattern] | |
const used = charSet.has(charWord) | |
const match = found && found === charWord | |
if (!found && !used) { | |
charMapping[charPattern] = charWord | |
charSet.add(charWord) | |
} else if (!match || (!found && used)) { | |
return false | |
} | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment