我正在尝试解决以下面试题:
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
我的做法是将长度为s.length - k
或更长的所有可能的字符串组合拿出来,例如当s为"abc"且k=1时,拿出来的字符串为:"ab" "bc" "ac" "abc"。然后检查它们是否是回文串。目前我已经有了以下代码,但似乎无法找到一种通用的方法来生成所有这些字符串组合:
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;
}
有没有人能想出一种实现这个的方法,或者展示一种更好的方法?
"abxa".equals(StringUtils.reverse("abxa"))
。 - Jorge Campos