迴文系列(JS)

LeetCode-迴文系列題

  1. 雙指針

125. 驗證迴文串

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;
};
複製代碼

9. 迴文數

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;
};
複製代碼

5. 最長迴文子串

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;
};
複製代碼

234. 迴文鏈表

  1. 快慢指針

快指針走兩步,慢指針走一步,快指針走到終點,慢指針走到一半bash

  1. 快慢指針走的同時,反轉慢指針的鏈表
/**
 * 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;
};
複製代碼
相關文章
相關標籤/搜索