|
| 1 | +# 1930. Unique Length-3 Palindromic Subsequences |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Hash Table, String, Prefix Sum. |
| 5 | +- Similar Questions: Count Palindromic Subsequences. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given a string `s`, return **the number of **unique palindromes of length three** that are a **subsequence** of **`s`. |
| 10 | + |
| 11 | +Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. |
| 12 | + |
| 13 | +A **palindrome** is a string that reads the same forwards and backwards. |
| 14 | + |
| 15 | +A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. |
| 16 | + |
| 17 | + |
| 18 | + |
| 19 | +- For example, `"ace"` is a subsequence of `"abcde"`. |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | +Example 1: |
| 24 | + |
| 25 | +``` |
| 26 | +Input: s = "aabca" |
| 27 | +Output: 3 |
| 28 | +Explanation: The 3 palindromic subsequences of length 3 are: |
| 29 | +- "aba" (subsequence of "aabca") |
| 30 | +- "aaa" (subsequence of "aabca") |
| 31 | +- "aca" (subsequence of "aabca") |
| 32 | +``` |
| 33 | + |
| 34 | +Example 2: |
| 35 | + |
| 36 | +``` |
| 37 | +Input: s = "adc" |
| 38 | +Output: 0 |
| 39 | +Explanation: There are no palindromic subsequences of length 3 in "adc". |
| 40 | +``` |
| 41 | + |
| 42 | +Example 3: |
| 43 | + |
| 44 | +``` |
| 45 | +Input: s = "bbcbaba" |
| 46 | +Output: 4 |
| 47 | +Explanation: The 4 palindromic subsequences of length 3 are: |
| 48 | +- "bbb" (subsequence of "bbcbaba") |
| 49 | +- "bcb" (subsequence of "bbcbaba") |
| 50 | +- "bab" (subsequence of "bbcbaba") |
| 51 | +- "aba" (subsequence of "bbcbaba") |
| 52 | +``` |
| 53 | + |
| 54 | + |
| 55 | +**Constraints:** |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | +- `3 <= s.length <= 105` |
| 60 | + |
| 61 | +- `s` consists of only lowercase English letters. |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +## Solution |
| 66 | + |
| 67 | +```javascript |
| 68 | +/** |
| 69 | + * @param {string} s |
| 70 | + * @return {number} |
| 71 | + */ |
| 72 | +var countPalindromicSubsequence = function(s) { |
| 73 | + var a = 'a'.charCodeAt(0); |
| 74 | + var res = 0; |
| 75 | + for (var i = 0; i < 26; i++) { |
| 76 | + var char = String.fromCharCode(i + a); |
| 77 | + var first = s.indexOf(char); |
| 78 | + var last = s.lastIndexOf(char); |
| 79 | + if (last - first < 2) continue; |
| 80 | + var map = {}; |
| 81 | + for (var j = first + 1; j < last; j++) { |
| 82 | + if (!map[s[j]]) { |
| 83 | + res += 1; |
| 84 | + map[s[j]] = true; |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + return res; |
| 89 | +}; |
| 90 | +``` |
| 91 | + |
| 92 | +**Explain:** |
| 93 | + |
| 94 | +nope. |
| 95 | + |
| 96 | +**Complexity:** |
| 97 | + |
| 98 | +* Time complexity : O(n). |
| 99 | +* Space complexity : O(1). |
0 commit comments