Leetcode 680 驗證迴文串II
阿新 • • 發佈:2022-03-14
c:
#include "stdbool.h" #include <string.h> int num = 0; bool palind(char *s, int left, int right) { if (left == right || left == right + 1) return true; if (s[left] == s[right]) return palind(s, left + 1, right - 1); if (num == 1) return false; num++;return palind(s, left + 1, right) || palind(s, left, right - 1); } bool validPalindrome(char *s) { if (s[0] == '\0') return true; return palind(s, 0, strlen(s) - 1); }
JAVA:
int num = 0; public boolean validPalindrome(String s) { int len = s.length(), left = 0, right = len - 1;return palind(s, left, right); } private boolean palind(String s, int left, int right) { if (left == right || left == right + 1) return true; if (s.charAt(left) == s.charAt(right)) return palind(s, left + 1, right - 1); if (num == 1) return false; num++;return palind(s, left, right - 1) || palind(s, left + 1, right); }
JS:
/** * @param {string} s * @return {boolean} */ var validPalindrome = function (s) { if (!s || s.length == 0) return true; return palind(s, 0, s.length - 1); }; var num = 0; var palind = function (s, left, right) { if (left == right || left == right + 1) return true; if (s.charAt(left) == s.charAt(right)) return palind(s, left + 1, right - 1); if (num == 1) return false; num ++; return palind(s, left + 1, right) || palind(s, left, right - 1); }