本文主要是介绍Leet Code OJ 125. Valid Palindrome [Difficulty: Easy] -python,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
125. Valid Palindrome
Easy
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
Constraints:
s
consists only of printable ASCII characters.
题意:
题目意思是判断输入字符串是否是回文串,只判断字符串中的数字和字母;并且空字符串也算回文字符串。
思路:
1.过滤字符串,用正则表达式\W过滤非数字和非字母;
2.判断字符串左右是否相等
代码:
#125 Valid Palindrome
class Solution(object):def isPalindrome(self, s):""":type s: str:rtype: bool"""if s=='' :return Trues1 = s.lower()s2 = re.sub('\W+','',s1).replace('_','')
# print(s2)l = len(s2)s3 = s2[::-1] #颠倒字符串if s2[0:int(l/2)]==s3[0:int(l/2)]:return Trueelse:return False
或者直接不颠倒,直接反向读取:这里注意反向读取字符串的写法:s2[:-(int(l/2)+1):-1],自己试了一下可以这样反向截取。
#125 Valid Palindrome
class Solution(object):def isPalindrome(self, s):""":type s: str:rtype: bool"""if s=='' :return Trues1 = s.lower()s2 = re.sub('\W+','',s1).replace('_','')
# print(s2)l = len(s2)print(int(l/2))
# s3 = s2[::-1]
# print(s2[0:int(l/2)],s2[:-(int(l/2)+1):-1])if s2[0:int(l/2)]==s2[:-(int(l/2)+1):-1]:return Trueelse:return False
这篇关于Leet Code OJ 125. Valid Palindrome [Difficulty: Easy] -python的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!