

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting all possible palindromic subsequence within a string in JavaScript
Palindrome Sequence:
A string sequence is known as palindrome sequence if it reads the same from front and the back. For instance, 'aba', 'madam, 'did' are all valid palindrome sequences.
We are required to write a JavaScript function that takes in a string as the first and the only argument. The string taken as input is guaranteed to consist of only 'a', 'b', 'c' and 'd'. Our function should count and return the number of all contiguous or noncontiguous palindrome subsequences that appear in the string.
For example −
If the input string is −
const str = 'bccb';
Then the output should be −
const output = 6;
because the palindrome strings here are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'
Example
The code for this will be −
const str = 'bccb'; const countPalindromes = (str = '') => { let base = 1000000007; const dp = Array(str.length).fill([]); for (let l = 1; l <= str.length; l ++) { for (let i = 0; i + l - 1 < str.length; i ++) { let j = i + l - 1; if (l === 1) { dp[i][j] = 1; continue; } if (l === 2) { dp[i][j] = 2; continue; } if (str[i] === str[j]) { let left = i + 1, right = j - 1; while (left <= right && str[left] != str[i]) { left ++; } while (left <= right && str[right] != str[i]) { right --; } if (left > right) { dp[i][j] = dp[i + 1][j - 1] * 2 + 2; } else if (left === right) { dp[i][j] = dp[i + 1][j - 1] * 2 + 1; } else { dp[i][j] = dp[i + 1][j - 1] * 2 - dp[left + 1][right - 1]; } } else { dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; } dp[i][j] = dp[i][j] < 0? dp[i][j] + base : dp[i][j] % base; } } return dp[0][str.length - 1]; }; console.log(countPalindromes(str));
Output
And the output in the console will be −
6
- Related Questions & Answers
- Count all Palindromic Subsequence in a given String in C++
- Counting possible APs within an array in JavaScript
- Longest Palindromic Subsequence
- Longest Palindromic Subsequence in C++
- Find the lexicographically largest palindromic Subsequence of a String in Python
- Java Program for Longest Palindromic Subsequence
- Print all palindromic partitions of a string in C++
- Find a palindromic string B such that given String A is a subsequence of B in C++
- Creating all possible unique permutations of a string in JavaScript
- JavaScript function that generates all possible combinations of a string
- Reversing words within a string JavaScript
- Sorting alphabets within a string in JavaScript
- Performing shifts within a string in JavaScript
- Counting prime numbers that reduce to 1 within a range using JavaScript
- Counting number of vowels in a string with JavaScript
Advertisements