
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Valid Palindrome in Python
- Palindrome Partitioning III in C++
- Valid Parentheses in C++
- Valid Sudoku in C++
- Palindrome Partitioning in C++
- Prime Palindrome in C++
- Palindrome Integer in C++
- Longest Palindrome in C++
- Shortest Palindrome in C++
- Valid Parenthesis String in C++
- Valid Triangle Number in C++
- Graph Valid Tree in C++
- Break a Palindrome in C++
- Palindrome Permutation II in C++
- Palindrome Partitioning II in C++
