高级农民
- 积分
- 2587
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2020-1-21
- 最后登录
- 1970-1-1
|
ChatGPT- import java.util.HashMap;
- import java.util.Map;
- public class Solution {
- private Map<String, Boolean> memo = new HashMap<>();
- public boolean validPalindrome(String s, int k) {
- return isValid(s, 0, s.length() - 1, k);
- }
- private boolean isValid(String s, int left, int right, int k) {
- // Base case: If k goes below 0, we can't delete more characters
- if (k < 0) return false;
- // Base case: If pointers cross, it's a palindrome or empty
- if (left >= right) return true;
- // Memoization: Avoid recalculating the same state
- String key = left + "," + right + "," + k;
- if (memo.containsKey(key)) return memo.get(key);
- boolean result;
- if (s.charAt(left) == s.charAt(right)) {
- // If characters match, move both pointers inward
- result = isValid(s, left + 1, right - 1, k);
- } else {
- // If characters don't match, try removing either left or right
- result = isValid(s, left + 1, right, k - 1) ||
- isValid(s, left, right - 1, k - 1);
- }
- // Store the result in the memo map and return
- memo.put(key, result);
- return result;
- }
- public static void main(String[] args) {
- Solution solution = new Solution();
- System.out.println(solution.validPalindrome("abca", 1)); // true
- System.out.println(solution.validPalindrome("abcdeca", 2)); // true
- System.out.println(solution.validPalindrome("abcdef", 1)); // false
- }
- }
复制代码 |
|