LeetCode 125 Valid Palindrome 回文字符串
描述
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
/**
* 忽略大小写
* 空字符串默认为true
* 首先正则去掉非字母和数字的字符
* 然后双指针从两端开始遍历,只要有一个不相等就返回false
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
const newStr = s.replace(/[^A-Za-z0-9]/g, '')
if (newStr === '') return true
let left = 0, right = newStr.length - 1
while(left < right){
if(newStr[left].toLocaleLowerCase() !== newStr[right].toLocaleLowerCase()){
return false
}
left ++
right --
}
return true
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!