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

12 Palindrome Partitioning

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

const isPalindrome = str => {
  if (str.length <= 1) {
    return true
  }
  if (str[0] !== str[str.length - 1]) {
    return false
  }
  return isPalindrome(str.slice(1, str.length - 1))
}

const palindromePartitioning = s => {
  const result = []
  const backtrack = (index, curr) => {
    if (index >= s.length) {
      result.push(curr.slice())
    }
    for (let i = index; i < s.length; i++) {
      const sub = s.slice(index, i + 1)
      if (isPalindrome(sub)) {
        curr.push(sub)
        backtrack(i + 1, curr)
        curr.pop()
      }
    }
  }
  backtrack(0, [])
  return result
}

console.log(palindromePartitioning('aab'))

Created 2022-02-28T06:17:56+00:00 · Edit