We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
125.验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama" 输出: true
示例 2:
输入: "race a car" 输出: false
https://leetcode-cn.com/problems/valid-palindrome
先根据题目给出的条件,通过正则把不匹配字符去掉,然后转小写。
建立双指针 i, j 分别指向头和尾,然后两个指针不断的向中间靠近,每前进一步就对比两端的字符串是否相等,如果不相等则直接返回 false。
i
j
如果直到 i >= j 也就是指针对撞了,都没有返回 false,那就说明符合「回文」的定义,返回 true。
i >= j
/** * @param {string} s * @return {boolean} */ let isPalindrome = function(s) { s = s.replace(/[^0-9a-zA-Z]/g, '').toLowerCase() let i = 0 let j = s.length - 1 while(i < j) { let head = s[i] let tail = s[j] if (head !== tail) { return false }else { i++ j-- } } return true };
The text was updated successfully, but these errors were encountered:
原题说是“我们将空字符串定义为有效的回文串。”,这个感觉答案里没有考虑到
Sorry, something went wrong.
No branches or pull requests
125.验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
示例 2:
https://leetcode-cn.com/problems/valid-palindrome
思路
先根据题目给出的条件,通过正则把不匹配字符去掉,然后转小写。
建立双指针
i
,j
分别指向头和尾,然后两个指针不断的向中间靠近,每前进一步就对比两端的字符串是否相等,如果不相等则直接返回 false。如果直到
i >= j
也就是指针对撞了,都没有返回 false,那就说明符合「回文」的定义,返回 true。The text was updated successfully, but these errors were encountered: