Valid Palindrome III in C++


Suppose we have a string s and another number k; we have to check whether the given string is a K-Palindrome or not.

A string is said to be K-Palindrome if it can be transformed into a palindrome by removing at most k characters from it.

So, if the input is like s = "abcdeca", k = 2, then the output will be true as by removing 'b' and 'e' characters, it will be palindrome.

To solve this, we will follow these steps −

  • Define a function lcs(), this will take s, t,

  • n := size of s

  • add one blank space before s

  • add one blank space before t

  • Define one 2D array dp of size (n + 1) x (n + 1)

  • for initialize i := 1, when i <= n, update (increase i by 1), do −

    • for initialize j := 1, when j <= n, update (increase j by 1), do −

      • dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]

      • if s[i] is same as t[j], then −

        • dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]

  • return dp[n, n]

  • From the main method do the following −

  • if not size of s, then −

    • return true

  • x := blank space

  • for initialize i := size of s, when i >= 0, update (decrease i by 1), do −

    • x := x + s[i]

  • return size of s

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int lcs(string s, string t){
      int n = s.size();
      s = " " + s;
      t = " " + t;
      vector<vector<int> > dp(n + 1, vector<int>(n + 1));
      for (int i = 1; i <= n; i++) {
         for (int j = 1; j <= n; j++) {
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            if (s[i] == t[j])
            dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);
         }
      }
      return dp[n][n];
   }
   bool isValidPalindrome(string s, int k) {
      if (!s.size())
      return true;
      string x = "";
      for (int i = s.size() - 1; i >= 0; i--)
         x += s[i];
      return s.size() - lcs(s, x) <= k;
   }
};
main(){
   Solution ob;
   cout << (ob.isValidPalindrome("abcdeca", 2));
}

Input

"abcdeca", 2

Output

1

Updated on: 11-Jul-2020

306 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements