125验证回文串,c语言判断是否为回文串


# 利用双指针,一次遍历,求出结果
class Solution:
def isPalindrome(self, s: str) -> bool:
# 定义变量,接收字符串的长度
length = len(s)
# 长度小于等于1直接返回真
if length <= 1:return True
# 定义两个指针, 分别指向字符串头和尾
index1,index2 = 0,length - 1
while index1 <= index2:
# 判断字符是否为字母或者数字
if not s[index1].isalnum():
index1 += 1
continue
if not s[index2].isalnum():
index2 -= 1
continue
# 判断两个字符是否相同
if s[index1].lower() != s[index2].lower():
return False
index1 += 1
index2 -= 1
return True

A = Solution()
print(A.isPalindrome("A man, a plan, a canal: Panama"))
print(A.isPalindrome(""))
print(A.isPalindrome("qq"))
print(A.isPalindrome("race a car"))


相关内容

    暂无相关文章

评论关闭