Create a bug report to help us improve our content -
Your email registered on BackToBackSWE :
Category of the bug :
[ ] Question
[X] Solution
[ ] Language
Description of the bug :
Code you used for Submit/Run operation :
const findAndReplacePattern = (words, pattern) => {
// create array literal to return matching patterns
const results = []
// iterate over the array of words
for(let i =0; i< words.length; i++){
// edge case if the length doesn't match skip it.
if(words[i].length != pattern.length){
continue;
}
// if the word matches the pattern push into results
// Use isMatch function break words down by characters and compare to pattern
if(isMatch(words[i], pattern)){
results.push(words[i])
}
}
// return array with patterns that match or empty array if no matches are found
return results;
}
// Determine if pattern matches word
const isMatch = (word, pattern) => {
// create data structure to store key value pairs to map pattern char to word char
const hash = new Map()
// iterate over the word (string) and look at each character
for(let i = 0; i < word.length; i++){
// if the letter from the pattern doesn't exist add to hash map
if(!hash.has(pattern[i])){
// set the key value pair for the mapping
hash.set(pattern[i], word[i])
}
// if the pattern char does exist, make sure it matches the word char it was originally mapped to - if not - return false
if(hash.get(pattern[i]) != word[i]){
return false
}
}
// if we break out of the loop we know it was a match and can return true
return true
}
Back To Back SWE
Create a bug report to help us improve our content -
Your email registered on BackToBackSWE :
Category of the bug :
Description of the bug :
Code you used for Submit/Run operation :
Language used for code :
JavaScript
Expected behavior :
Screenshots :
Additional context :