1930. Unique Length-3 Palindromic Subsequences #1071
-
Topics: Given a string Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. 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.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use an efficient algorithm that leverages prefix and suffix character tracking to count all valid palindromic subsequences. Approach
Let's implement this solution in PHP: 1930. Unique Length-3 Palindromic Subsequences <?php
/**
* @param String $s
* @return Integer
*/
function countPalindromicSubsequence($s) {
$n = strlen($s);
$prefix = array_fill(0, $n, []);
$suffix = array_fill(0, $n, []);
// Track prefix characters
$seen = [];
for ($i = 0; $i < $n; $i++) {
$prefix[$i] = $seen;
$seen[$s[$i]] = true;
}
// Track suffix characters
$seen = [];
for ($i = $n - 1; $i >= 0; $i--) {
$suffix[$i] = $seen;
$seen[$s[$i]] = true;
}
// Track unique palindromic subsequences
$uniquePalindromes = [];
// Check for each character as the middle character
for ($i = 1; $i < $n - 1; $i++) {
foreach ($prefix[$i] as $char1 => $true) {
if (isset($suffix[$i][$char1])) {
$palindrome = $char1 . $s[$i] . $char1;
$uniquePalindromes[$palindrome] = true;
}
}
}
// Return the count of unique palindromic subsequences
return count($uniquePalindromes);
}
// Test cases
echo countPalindromicSubsequence("aabca") . PHP_EOL; // Output: 3
echo countPalindromicSubsequence("adc") . PHP_EOL; // Output: 0
echo countPalindromicSubsequence("bbcbaba") . PHP_EOL; // Output: 4
?> Explanation:
Complexity
OutputThe code produces the correct results for the given examples:
|
Beta Was this translation helpful? Give feedback.
We can use an efficient algorithm that leverages prefix and suffix character tracking to count all valid palindromic subsequences.
Approach
Track Prefix Characters:
Use an array to store the set of characters encountered to the left of each position in the string. This will help in efficiently checking if a character can form the first part of a palindromic subsequence.
Track Suffix Characters:
Use another array to store the set of characters encountered to the right of each position in the string. This will help in efficiently checking if a character can form the third part of a palindromic subsequence.
Count Palindromic Subsequences:
For each character in the string, consider it a…