您的位置:首页 > 编程语言 > Python开发

[leetcode] 125. Valid Palindrome

2016-04-20 10:50 507 查看

题目描述:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,

“A man, a plan, a canal: Panama” is a palindrome.

“race a car” is not a palindrome.

Note:

Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

题意:

判断去除空格和标点后的字符串是否为回文,即所谓的有效回文判断。

python代码:

class Solution:
# @param {string} s A string
# @return {boolean} Whether the string is a valid palindrome
def isPalindrome(self, s):
start, end = 0, len(s) - 1
while start < end:
while start < end and not s[start].isalpha() and not s[start].isdigit():
start += 1
while start < end and not s[end].isalpha() and not s[end].isdigit():
end -= 1
if start < end and s[start].lower() != s[end].lower():
return False
start += 1
end -= 1
return True


Python isalpha()方法

描述:检测字符串是否只由字母组成。

参数:

返回值:如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回 False

Python isdigit()方法

**描述:**Python isdigit() 方法检测字符串是否只由数字组成。

**语法:**str.isdigit()

参数:无。

返回值:如果字符串只包含数字则返回 True 否则返回 False。

程序思路:逐个判断,如果不是字母或者数字就移动start和end指针;否则判断两指针对应的字符是否相同,从而判断是否为回文。

我的代码:

class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""

from string import punctuation
# s = s.replace(s.punctuation,"")
# s.translate(None, punctuation)
s = "".join(s.split())
s = "".join([c for c in s if c not in punctuation])
start = 0
end = len(s) - 1
if start == end:
return True
while start < end:
if s[start].lower() == s[end].lower():
start = start + 1
end = end - 1
else:
return False
return True


我的思路是先去掉空格和标点符号。由于去掉空格和标点符号都要对字符串进行一次遍历,所以复杂度就高了T^T。

不过这里还学了挺多的,比如怎么去掉空格和标点符号,还有python是大小写敏感的,就需要转换一下[用upper(),lower()]才可以比较。

知识补充:

字符串去掉标点符号:

参考:http://www.itstrike.cn/Question/5860b8a2-6c44-44f4-8726-c5a7603d44cc.html

使用str.translate:

from string import punctuation
[ x.translate(None, punctuation) for x in lis]


from string import punctuation
strs.translate(None, punctuation)


使用正则表达式:

import re
[ re.sub(r'[{}]+'.format(punctuation),'',x ) for x in lis]


re.sub(r'[{}]+'.format(punctuation),'', strs)


使用list的comprehension和str.join:

["".join([c for c in x if c not in punctuation]) for x in lis]


"".join([c for c in strs if c not in punctuation])


其实还是有点问题的,因为用的前两种,好像编译时候还是不行。

使用translate时候会提醒translate只需要一个参数。好吧,还是需要看看python学习手册。慢慢解决。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python