LeetCode(125)--Valid Palindrome
2015-12-01 10:48
344 查看
题目如下:
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.
解题思路:
求回文的题目无论是在研究生入学考试,还是在面试中时有出现。本题是忽略空格、字符、大小写的约束,来判断一句话的内容是否是回文。通过对字符串从两端进行扫描,如果有字母就进行比较,如果不是将该字符忽略找到下一个字符。本题的思路使我们联想起折半查找方法。
提交的代码:
该方法的时间复杂度是O(N),在线性的时间内完成了回文的搜索。
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.
解题思路:
求回文的题目无论是在研究生入学考试,还是在面试中时有出现。本题是忽略空格、字符、大小写的约束,来判断一句话的内容是否是回文。通过对字符串从两端进行扫描,如果有字母就进行比较,如果不是将该字符忽略找到下一个字符。本题的思路使我们联想起折半查找方法。
提交的代码:
public boolean isPalindrome(String s) { if(s == null || s.length() == 0) return true; int i = 0; int j = s.length() - 1; while(i < j) { while(i < j && !Character.isLetterOrDigit(s.charAt(i))) i++; while(i < j && !Character.isLetterOrDigit(s.charAt(j))) j--; if(Character.toLowerCase(s.charAt(i++)) == Character.toLowerCase(s.charAt(j--))){ continue; }else{ return false; } } return true; }
该方法的时间复杂度是O(N),在线性的时间内完成了回文的搜索。
相关文章推荐
- Javascript操作DOM常用API总结
- BootStrap带样式打印
- 文件上传
- # 信息安全系统设计基础 实验三
- 搭建springMVC+Mybatis的Maven项目过程中遇到的问题汇总。
- Android DiskLruCache 摘录
- 剑招offer之重建二叉树
- LeetCode OJ——Basic Calculator
- oracle exp imp 备份 还原
- .NET(C#):await返回Task的async方法
- PHP开启伪静态配置
- Linux 分区注意事项
- 分享PHP源码批量抓取远程网页图片并保存到本地的实现方法
- android下的事件分发
- QoS/ToS/CoS/DSCP 介绍
- python转C的内存泄露问题
- sample questions
- AngularJS的Provider, Value, Constant, Service, Factory, Decorator的区别与详解
- 常见算法:C语言求素数的问题
- jsp九大内置对象详解