Counting Palindromic Subsequences in a String
Sun Mar 10 2024
stringSubsequence :
Method to count all palindromic subsequences in a given string, excluding the empty string. This solution generates all possible subsequences of the input string using recursion and checks each for palindromicity. By avoiding the inclusion of the empty subsequence in the final count, the method provides an accurate total of palindromic subsequences present.
1function reverseString(string) {
2  let strArray = string.split("");
3  let start = 0;
4  let end = strArray.length - 1;
5  let temp = "";
6  while (start < end) {
7    temp = strArray[end];
8    strArray[end] = strArray[start];
9    strArray[start] = temp;
10    start++;
11    end--;
12  }
13  return strArray.join("");
14}
15
16function isStringPalindrome(string) {
17  return string === reverseString(string);
18}
19let element = [];
20function stringSubsequence(input, output) {
21  if (input.length === 0) {
22    isStringPalindrome(output) && element.push(output);
23    return;
24  }
25  stringSubsequence(input.substring(1), output);
26  stringSubsequence(input.substring(1), output + input[0]);
27}
28
29const inputString = "abc";
30const inputString1 = "abcd";
31const inputString2 = "aab";
32// stringSubsequence(inputString, "");
33// stringSubsequence(inputString1, "");
34stringSubsequence(inputString2, "");
35console.log(element.length - 1);
36