leetcode with python: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.

给定一个字串,检测字母全部转小写,去除非数字字母的元素及空白后该字串是否对称
ex:input:"A man, a plan, a canal: Panama"=>output:True
explanation:"amanaplanacanalpanama" is a palindrome.

解这题目时我在网上查到了isalnum()这个函数
可以用来判断该字串是否由字母或数字组成,让这题轻鬆许多

class Solution:    def isPalindrome(self, s: str) -> bool:        s=s.lower()        p=0        q=len(s)-1        while p<q:            while p<q and not s[p].isalnum():                p=p+1                                while q>p and not s[q].isalnum():                q=q-1                                if s[p].isalnum() and s[q].isalnum():                if s[p]==s[q]:                    p=p+1                    q=q-1                else:                    return False           return True

先将字串内所有字母转为小写
接着一个指标从前,一个指标从后,遇到字母及数字(用isalnum判断)才停下判断
两者一有不同就回传False,直到两个指标交错
都没侦测到False的状况就回传True
最后执行时间49ms(faster than 89.89%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章