I'm trying to solve the following interview practice question:
A k-palindrome is a string which transforms into a palindrome on removing at most k characters.
Given a string S, and an integer K, print "YES" if S is a k-palindrome; otherwise print "NO".
Constraints:
S
has at most 20,000 characters.
0 <= k <= 30
Sample Test Cases:
Input - abxa 1 Output - YES Input - abdxa 1 Output - NO
My approach I've decided is going to be taking all possible String combinations of length s.length - k
or greater, i.e. "abc" and k = 1 -> "ab" "bc" "ac" "abc" and checking if they are palindromes. I have the following code so far, but can't seem to figure out a proper way to generate all these string combinations in the general case:
public static void isKPalindrome(String s, int k) {
// Generate all string combinations and call isPalindrome on them,
// printing "YES" at first true
}
private static boolean isPalindrome(String s) {
char[] c = s.toCharArray()
int slow = 0;
int fast = 0;
Stack<Character> stack = new Stack<>();
while (fast < c.length) {
stack.push(c[slow]);
slow += 1;
fast += 2;
}
if (c.length % 2 == 1) {
stack.pop();
}
while (!stack.isEmpty()) {
if (stack.pop() != c[slow++]) {
return false;
}
}
return true;
}
Can anyone figure out a way to implement this, or perhaps demonstrate a better way?