code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

290 Word Pattern

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const wordPattern = (pattern, s) => {
  const sArray = s.split(' ')
  if (pattern.length !== sArray.length) {
    return false
  }
  let patternToMap = {}
  let sToMap = {}
  for (let i = 0; i < pattern.length; i++) {
    if (patternToMap[pattern[i]]) {
      if (patternToMap[pattern[i]] != sArray[i]) {
        return false
      }
    } else {
      patternToMap[pattern[i]] = sArray[i]
    }
    if (sToMap[sArray[i]]) {
      if (sToMap[sArray[i]] != pattern[i]) {
        return false
      }
    } else {
      sToMap[sArray[i]] = pattern[i]
    }
  }
  return true
}

console.log(wordPattern('abba', 'dog cat cat dog'))

Created 2022-03-21T17:13:32+00:00 · Edit