如何判断自己解决回文类问题的解法是否 高效?其中一个很重要的标准,就是看你对回文字符串的对称特性利用得是否彻底。
实现思路:
const validPalindrome = function(s) {let start = 0,end = s.length - 1;while (start < end) {if (s[start] !== s[end]) {// 转为判断删掉字符后的子字符,是否是回文串return isPalindrome(s, start + 1, end) || isPalindrome(s, start, end - 1);}start++;end--;}function isPalindrome(str, start, end) {while (start < end) {// 一票否决if (str[start] !== str[end]) {return false;}start++;end--;}return true;}return true;};
const validPalindrome = function(s) {let start = 0,end = s.length - 1;while (start <= end) {if (s[start] === s[end]) {start++;end++;} else {break;}}if (start > end) {return true;} else {let tmpStart = start,tmpEnd = end;// 删除做指针指向的字符start++;while (start <= end) {if (s[start] === s[end]) {start++;end--;} else {break;}}if (start > end) return true;// 此路不通,复位,删除缩小范围的结束指针指向的字符start = tmpStart;end = tmpEnd;end--;while (start <= end) {if (s[start] === s[end]) {start++;end--;} else {break;}}if (start > end) {return true;}}return false;};