You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> Given a string, find the minimum number of characters that we can remove to make it a <i>palindrome</i>.
3714
+
3715
+
#### Example 1:
3716
+
```js
3717
+
Input:"abdbca"
3718
+
Output:1
3719
+
Explanation: By removing "c", we get a palindrome "abdba".
3720
+
```
3721
+
#### Example 2:
3722
+
```js
3723
+
Input:="cddpd"
3724
+
Output:2
3725
+
Explanation: Deleting "cp", we get a palindrome "ddd".
3726
+
```
3727
+
#### Example 3:
3728
+
```js
3729
+
Input:="pqr"
3730
+
Output:2
3731
+
Explanation: We have to remove any two characters to get a palindrome,
3732
+
e.g. if we remove "pq", we get palindrome "r".
3733
+
```
3734
+
3735
+
This problem can be easily converted to the <b>[Longest Palindromic Subsequence (LPS)](#longest-palindromic-subsequence)</b> problem. We can use the fact that <b>LPS</b> is the best subsequence we can have, so any character that is not part of <b>LPS</b> must be removed. Please note that it is [‘Longest Palindromic SubSequence’](#longest-palindromic-subsequence) and not [‘Longest Palindrome Substring’](#👩🏽🦯-🌴-longest-palindromic-substring).
3736
+
3737
+
So, our solution for a given string `str` will be:
Any string will be called `K`<b>-palindromic</b> if it can be transformed into a <i>palindrome</i> by removing at most `K` characters from it.
3894
+
3895
+
This problem can easily be converted to our base problem of <i>finding the minimum deletions in a string to make it a palindrome</i>. If the <i>“minimum deletion count”</i> is not more than `K`, the string will be `K`<b>-palindromic</b>.
3896
+
```js
3897
+
functionisValidPalindrome(s, K) {
3898
+
functionfindLPSLength(s) {
3899
+
// dp[i][j] stores the length of LPS from index 'i' to index 'j'
3900
+
constdp=Array(s.length)
3901
+
.fill(0)
3902
+
.map(() =>Array(s.length).fill(0));
3903
+
3904
+
//every sequence with one element is a palindrome of length 1
3905
+
for (let i =0; i <s.length; i++) dp[i][i] =1;
3906
+
3907
+
for (let startIndex =s.length-1; startIndex >=0; startIndex--) {
3908
+
for (let endIndex = startIndex +1; endIndex <s.length; endIndex++) {
3909
+
// case: 1 elements at the beggining and end are the same
0 commit comments