Skip to main content

1930.js

/** ------------------------------------------------------------------------------
*
* 1930. Unique Length-3 Palindromic Subsequences
* Topics: String, Hash Table
* https://leetcode.com/problems/unique-length-3-palindromic-subsequences/?envType=daily-question&envId=2025-01-04
*
------------------------------------------------------------------------------ */
/**
* @param {string} s
* @return {number}
*/
var countPalindromicSubsequence = function (s) {
let answer = 0
const first = Array(26).fill(-1)
const last = Array(26).fill(-1)

for (let i = 0; i < s.length; i++) {
const j = s.charCodeAt(i) - "a".charCodeAt(0)
if (first[j] === -1) {
first[j] = i
}
last[j] = i
}

for (let i = 0; i < 26; i++) {
if (first[i] === -1 || first[i] === last[i]) continue

const l = first[i],
r = last[i]
const mids = new Set()
for (let j = l + 1; j < r; j++) {
mids.add(s[j])
}
answer += mids.size
}
return answer
}

/**
* indexOf, lastIndexOf 사용한 간단풀이
*/
var countPalindromicSubsequence = function (s) {
let answer = 0
const uniq = new Set(s)

for (const c of uniq) {
const start = s.indexOf(c)
const end = s.lastIndexOf(c)

if (start < end) {
answer += new Set(s.slice(start + 1, end)).size
}
}
return answer
}

console.log(countPalindromicSubsequence("aabca"))