Unique Length-3 Palindromic Subsequences

medium string hashing

Problem

Return the number of distinct length-3 palindromic subsequences of s. Palindromes have the form c·x·c.

Inputs = "aabca"
Output3
"aaa", "aba", "aca".

def count_palindromic_subsequence(s):
    total = 0
    for c in set(s):
        first = s.find(c)
        last = s.rfind(c)
        if last > first + 1:
            total += len(set(s[first + 1:last]))
    return total
function countPalindromicSubsequence(s) {
  let total = 0;
  for (const c of new Set(s)) {
    const first = s.indexOf(c), last = s.lastIndexOf(c);
    if (last > first + 1) total += new Set(s.slice(first + 1, last)).size;
  }
  return total;
}
class Solution {
    public int countPalindromicSubsequence(String s) {
        int total = 0;
        for (char c = 'a'; c <= 'z'; c++) {
            int first = s.indexOf(c), last = s.lastIndexOf(c);
            if (last > first + 1) {
                Set<Character> set = new HashSet<>();
                for (int i = first + 1; i < last; i++) set.add(s.charAt(i));
                total += set.size();
            }
        }
        return total;
    }
}
int countPalindromicSubsequence(string s) {
    int total = 0;
    for (char c = 'a'; c <= 'z'; c++) {
        size_t first = s.find(c), last = s.rfind(c);
        if (first == string::npos || last == first) continue;
        if (last > first + 1) {
            unordered_set<char> set;
            for (size_t i = first + 1; i < last; i++) set.insert(s[i]);
            total += set.size();
        }
    }
    return total;
}
Time: O(26·n) Space: O(26)