LeetCode:验证回文字符串(Python版本)
2019-03-18 09:56
731 查看
LeetCode刷题日记
验证回文字符串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明: 本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
示例 2:
输入: “race a car”
输出: false
Python代码
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ convert = [] # 提取数字和字母 lows = s.lower() # 大写转换为小写 for i in lows: if i.isalpha() or i.isdigit(): convert.append(i) if len(convert) == 1 or not convert: # 包含一个字符和空都为true return True if len(convert) == 2: if convert[0] == convert[1]: return True for i in range(len(convert) // 2): if convert[i] == convert[-i - 1]: if i == len(convert) // 2 - 1: return True continue else: return False
一开始做这个忘了考虑字符串应该还有数字,考虑不周啊。。
- 补充:刚看到一个比较好的回文字符串比较方法,贴到这里来:
lst == lst[::-1]
大概意思是这样的:
如果
list = [1 , 2 , 3 , 4 , 5],那么
list[ : : -1] = [5 , 4 , 3 , 2 , 1]
相关文章推荐
- leetcode-验证回文字符串
- [LeetCode] 680. Valid Palindrome II 验证回文字符串 II
- LeetCode:字符串转换整数 (atoi)(Python版本)
- [LeetCode] Valid Palindrome II 验证回文字符串之二
- LeetCode 125. Valid Palindorme (验证回文字符串)
- golang_算法: leetcode_字符串05-验证回文字符串
- LeetCode-探索-初级-字符串-验证回文字符串-java
- LeetCode 680. Valid Palindrome II (验证回文字符串 Ⅱ)
- LeetCode 415. Add Strings(字符串相加)python3版本
- [LeetCode 125] - 验证回文(Valid Palindrome)
- LeetCode:搜索二维矩阵 II(Python版本)
- LeetCode:分割回文串(Python版本)
- 请尝试写一个验证Email地址的正则表达式。版本一应该可以验证出类似的Email —— python学习笔记
- leetcode 409. Longest Palindrome 可以构造的最长的回文字符串
- iap支付服务器验证python版本
- Leetcode 125. Valid Palindrome 回文验证 解题报告
- [leetcode, python] Reverse Words in a String 反转字符串
- Python回文字符串及回文数字判定功能示例
- python 回文字符串 回文数字
- Python字符串处理(版本2.7)-学习笔记