var isPalindrome = function (s) {
if (s === '') return true;
let reg = /[^A-Za-z0-9]/g// ^表示匹配除了中括號外的字符
let str = s.replace(reg, '').toLowerCase();
let l = 0, r = str.length - 1;
while (l < r) {
if (str[l++] !== str[r--]) return false;
}
return true;
};
複製代碼
var isPalindrome = function (x) {
if (x < 10 && x >= 0) return true;
const nums = x.toString().split('');
let l = 0, r = nums.length - 1;
while (l < r)
if (nums[l++] !== nums[r--]) return false;
return true;
};
複製代碼
var longestPalindrome = function (s) {
let ans = '', n = s.length;
for (let i = 0; i < n; i++) {
for (let j = i, k = i; j >= 0 && k < n && s[j] === s[k]; j-- , k++)
if (ans.length < k - j + 1) ans = s.substr(j, k - j + 1);
for (let j = i, k = i + 1; j >= 0 && k < n && s[j] === s[k]; j-- , k++)
if (ans.length < k - j + 1) ans = s.substr(j, k - j + 1);
}
return ans;
};
複製代碼
快指針走兩步,慢指針走一步,快指針走到終點,慢指針走到一半bash
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function (head) {
if (head && head.next === null) return true;
let fast = head, slow = head;
let pre = null, s = null; // s 至關於上一個鏈表
while (fast !== null && fast.next !== null) {
pre = slow;
fast = fast.next.next; // 走兩步
slow = slow.next;
// 反轉前半部分鏈表
pre.next = s;
s = pre;
}
let tmp = slow;
// fast = null 偶數
// fast !== null 奇數,tmp走到下一步,去掉中間的數
if (fast !== null) tmp = tmp.next;
slow = pre;
while (tmp !== null) {
if (tmp.val !== slow.val) return false;
else {
tmp = tmp.next;
slow = slow.next;
}
}
return true;
};
複製代碼