K Palindrome
A string is a k-palindrome if it can be transformed into a palindrome by removing any amount of characters from 0
to k
. Your task is to determine whether the given string s
is a k-palindrome.
Example
For
s = "abrarbra"
andk = 1
, the output should bekpalindrome(s, k) = true
.You can remove one letter,
'r'
, to obtain the string"abrarba"
, which is a palindrome.For
s = "adbcdbacdb"
andk = 2
, the output should bekpalindrome(s, k) = false
.
Input/Output
[execution time limit] 3 seconds (java)
[input] string s
A string containing only lowercase English letters.
Guaranteed constraints:
3 ≤ s.length ≤ 100
.[input] integer k
Guaranteed constraints:
1 ≤ k ≤ 20
.[output] boolean
- Return
true
if it is possible to delete at mostk
letters from a strings
in order to make it palindrome. Returnfalse
otherwise.
- Return
boolean kpalindrome(String s, int k) { | |
Boolean[][] memo = new Boolean[s.length()][s.length()]; | |
return dfs(s, k, 0, s.length() - 1, memo); | |
} | |
boolean dfs(String s, int k, int lo, int hi, Boolean[][] memo) { | |
if (lo >= hi) { | |
return true; | |
} | |
if (memo[lo][hi] != null) { | |
return memo[lo][hi]; | |
} | |
while (lo < hi) { | |
if (s.charAt(lo) != s.charAt(hi)) { | |
break; | |
} | |
lo++; | |
hi--; | |
} | |
boolean ans = k >= 0 && (dfs(s, k - 1, lo + 1, hi, memo) || dfs(s, k - 1, lo, hi - 1, memo)); | |
memo[lo][hi] = ans; | |
return ans; | |
} |