验证回文串
题目链接: https://leetcode.cn/problems/valid-palindrome/
视频题解: https://www.bilibili.com/video/BV1VH4y1P7Gk/
# LeetCode 125. 验证回文串
# 题目描述
如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。
字母和数字都属于字母数字字符。
给你一个字符串 s
,如果它是 回文串 ,返回 true
;否则,返回 false
。
举个例子:
输入: s = "A man, a plan, a canal: Panama"
输出:true
解释:"amanaplanacanalpanama" 是回文串。
# 视频讲解
建议大家点击视频跳转到b站验证回文串 (opens new window)观看,体验更佳!
# 思路解析
先明确回文串的概念:正着读和反着读都一样。换句话说就是对于字符串s
,将s
进行反转得到字符串s'
,如果s == s'
,那么s
就是回文串。
本题中的字符串s
包含一些非字母数字干扰字符,在判断的时候可以跳过干扰字符。
采用双指针法,定义两个变量left = 0
,right = s.length() - 1
。
- 当
left < right
,left
向右移动,直到left
指向字母或数字,right
向左移动,直到right
指向字母或数字。如果left >= right
说明s
是回文串,否则进入步骤2
。 - 比较
left
和right
指向字符对应的小写字符是否相等,如果不相等说明s
不是回文串,否则left
和right
同时移动,++left
,--right
,进入步骤1
。
# C++代码
class Solution {
public:
bool isPalindrome(string s) {
//定义两个索引
int left = 0, right = s.length() - 1;
while (left < right) {
//left需要指在字母或数字上
while (left < right && !isalnum(s[left])) {
++left;
}
//right需要指在字母或数字上
while (left < right && !isalnum(s[right])) {
--right;
}
if (tolower(s[left]) != tolower(s[right])) {
return false;
}
++left;
--right;
}
return true;
}
};
# java代码
class Solution {
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
//left需要指在字母或数字上
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
++left;
}
//right需要指在字母或数字上
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
--right;
}
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
++left;
--right;
}
return true;
}
}
# python代码
class Solution:
def isPalindrome(self, s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
#left需要指在字母或数字上
while left < right and not s[left].isalnum():
left += 1
#right需要指在字母或数字上
while left < right and not s[right].isalnum():
right -= 1
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return True
# 复杂度分析
时间复杂度: 只需要遍历一遍字符串,所以时间复杂度为O(n),其中n
为字符串的长度。
空间复杂度: 只使用了两个索引,所以空间复杂度为O(1)。
上次更新: 2024/07/13, 21:23:13