LeetCode刷题 (Python) | 125. Valid Palindrome
2016-01-30 20:34
746 查看
题目链接
https://oj.leetcode.com/problems/valid-palindrome/心得
本身没什么难度,还是在于对原始字符串的处理。python的库实在是全面,用了两个函数就把原始字符串处理完了。需要注意的是,处理之后的字符串不要保存到string里,那样会超时,应该用list保存。具体原因不详,和python的实现有关,希望指点。AC代码
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ s = s.lower() string = [] for c in s: if c.isalnum(): string.append(c) i, j = 0, len(string)-1 while i < j: if string[i] != string[j]: return False i += 1 j -= 1 return True if __name__ == "__main__": solution = Solution() print(solution.isPalindrome('aa'))
耗时88ms。
在讨论区看到一个更简洁的版本,也是88ms。
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ cleanlist = [c for c in s.lower() if c.isalnum()] return cleanlist == cleanlist[::-1]
相关文章推荐
- python中global 和 nonlocal 的作用域
- 笔试题-搜狐手机网Python开发工程师
- python资源整理
- 编写高质量代码--改善python程序的建议(八)
- Python 8.5 分布式进程
- LeetCode刷题 (Python) | 155. Min Stack
- Python多线程学习
- python 文件、目录属性的操作os.path等os模块函数
- python学习笔记之四
- 不简单的python- 02函数类异常处理
- Python教程学习简记1--Python数据类型和变量 字符串和编码 list和tuple 条件判断 循环 dict和set
- python学习笔记三
- 『Python』序列学习总结之二——元组
- python 文件读写
- 不简单的python- 01基础
- Python面向对象编程(二)
- Python 面向对象编程(一)
- spark 常用python API
- python 文件读写
- Python学习一:环境搭建