【LeetCode】125、Valid Palindrome
来源:互联网 发布:学python能做什么 编辑:程序博客网 时间:2024/05/16 10:03
1、题目描述:
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? is is a good question to ask during an
interview.
For the purpose of this problem, we define empty string as valid palindrome.
2.1、可以看出标点符号、空格是舍去不计的,大小写之间是没有差别的、大写小写字母之间需要相互转化。
2.2、知识点:如果我们不是以除正常方式以外的其他任意方式退出循环(即满足前面的循环结束条件,正常循环结束,执行else),那么else分支将被执行。也就是在循环体内没有break语句、没有return语句,或者没有异常出现,则将会执行else。
可以记忆为:for else是一体的结构,break跳出这整个结构当然不会执行结构内部的else语句。
3、解答:Python strip() 方法用于移除字符串头尾指定的字符(默认为空格,且需注意只能移除首尾指定的字符);
ASCII码和数字之间的转化: ord('a') 和chr(59) 。ord函数利用字符求得ASCII数字,chr函数利用ASCII数字求得字符;
大小写字母的取值范围是,其他不在此范围之内的都不是字母(48-57: "0"--"9"; 65-90: "A"--"Z"; 97-122: "a"--"z");
参见:http://blog.csdn.net/mtbaby/article/details/54907454
大小写之间的相互转化有upper() 、lower() 函数;判断字符是否是字母(isalpha())、数字(isdigit())、字母加数字(isalnum())
class Solution: # @param s, a string # @return a boolean def isPalindrome(self, s): newS= [i.lower() for i in s if i.isalnum()] #return newS == newS[::-1] return newS[:len(newS)/2] == newS[(len(newS)+1)/2:][::-1]
另一种代码:
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ start = 0 end = len(s)-1 while start < end: while start < end and not s[start].isdigit() and not s[start].isalpha(): start += 1 while start < end and not s[end].isdigit() and not s[end].isalpha(): end -=1 if s[start].lower() != s[end].lower(): return False start += 1 end -= 1 else: return True
- LeetCode 125: Valid Palindrome
- LeetCode 125 Valid Palindrome
- LeetCode: Valid Palindrome [125]
- leetcode 125-Valid Palindrome
- [leetcode 125] Valid Palindrome
- leetCode #125 Valid Palindrome
- [LeetCode 125] Valid Palindrome
- LeetCode 125 Valid Palindrome
- leetcode-125 Valid Palindrome
- leetcode || 125、Valid Palindrome
- LeetCode---(125) Valid Palindrome
- Leetcode[125]-Valid Palindrome
- leetcode[125]:Valid Palindrome
- Leetcode# 125 Valid Palindrome
- leetcode 125: Valid Palindrome
- leetcode: (125) Valid Palindrome
- [Leetcode]#125 Valid Palindrome
- LeetCode 125 Valid Palindrome
- 脑袋里是浆糊时的c++程序(我一定是傻了)
- JS代码
- Struts2(6)——Action传递参数
- ADM打不开/data,或打开后无法导出里面的文件
- ACM 括号匹配深度
- 【LeetCode】125、Valid Palindrome
- 移动端踩坑之旅-ios下fixed、软键盘相关问题总结
- ajax跨域传递cookie,验证登录
- 1.虚拟机
- intelliJ idea 导入eclipse/myeclipse web project
- ubuntu16 caffe安装+测试(cpu)
- Java多线程基础——线程和线程安全
- 决策树算法详解(2)
- java集合类总结