1930. Unique Length-3 Palindromic Subsequences

T: O(n + 26n)
S: O(26)

```java
class Solution {
    public int countPalindromicSubsequence(String s) {
        int[] firstOccur = new int[26];
        int[] lastOccur = new int[26];
        Arrays.fill(firstOccur, -1);

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (firstOccur[c - 'a'] == -1) {
                firstOccur[c - 'a'] = i;
            }
            lastOccur[c - 'a'] = i;
        }

        int result = 0;
        Set<Character> countSet = new HashSet<>();
        for (int i = 0; i < 26; i++) {
            if (firstOccur[i] != -1 && lastOccur[i] != -1) {
                countSet = new HashSet<>();
                for (int j = firstOccur[i]+1; j < lastOccur[i]; j++) {
                    countSet.add(s.charAt(j));
                }
                result += countSet.size();
            }
        }
        return result;
    }
}

/**

T: O(n + 26n)
S: O(26)

first[] record smallest index of String s's char

why Arrays.fill(firstOccur, -1);
because we only want ""first"" occur, so if it's -1, it's the first one char in index


last[] record largest index...

i = 0 ~ 25
then cal between first[i] and last[i]
how many distinct char there

sum them all, it's the ans

ex: 
because we ask for len 3 palindrom... so first and third must be the same, then we only need to cal between 
these first and third, how many distinct char 


aabca

  abc -> 3 different char  
a     a

and we can find another pair (first and third) is the same, so...
ans = 3

-> ex: this is cal between a and a, there are how many distinct char
for (int j = firstOccur[i]+1; j < lastOccur[i]; j++) {

 */
```

Last updated