Skip to content

Latest commit

 

History

History
43 lines (34 loc) · 909 Bytes

125. 验证回文串.md

File metadata and controls

43 lines (34 loc) · 909 Bytes
  • 双指针
/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function (s) {
    let leftIndex = 0,
        rightIndex = s.length - 1;

    while (leftIndex < rightIndex) {
        while (leftIndex < rightIndex && !isValidCharacter(s[leftIndex])) {
            ++leftIndex;
        }

        while (leftIndex < rightIndex && !isValidCharacter(s[rightIndex])) {
            --rightIndex;
        }

        if (leftIndex >= rightIndex) {
            break;
        }

        if (s[leftIndex].toLowerCase() !== s[rightIndex].toLowerCase()) {
            return false;
        }

        ++leftIndex;
        --rightIndex;
    }

    return true;
};

function isValidCharacter(ch) {
    return (ch >= 'a' && ch <= 'z') ||
        (ch >= 'A' && ch <= 'Z') ||
        (ch >= '0' && ch <= '9');
}