javascript-leetcode icon indicating copy to clipboard operation
javascript-leetcode copied to clipboard

125. 验证回文串

Open Geekhyt opened this issue 4 years ago • 0 comments

原题链接

双指针

先明确题意,题目要求只考虑字母和数字字符,并且可以忽略大小写。

1.首先用正则去掉字符串中不是字母和数字的元素,并且都转换成小写。 2.借助双指针 left, right 进行夹逼比较。 3.如果 s[left] 和 s[right] 每一项都相等,则是回文串,否则就不是回文串。

const isPalindrome = function (s) {
    s = s.replace(/[^0-9a-zA-Z]/g, '').toLowerCase()
    let n = s.length, left = 0, right = n - 1;
    while (left < right) {
        if (s[left] !== s[right]) {
            return false
        }
        left++
        right--
    }
    return true
}
  • 时间复杂度: O(∣s∣), 其中 ∣s∣ 是字符串 s 的长度
  • 空间复杂度: O(1)

Geekhyt avatar Feb 22 '21 04:02 Geekhyt