您的位置:首页 > 其它

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.

解题思路:

求回文的题目无论是在研究生入学考试,还是在面试中时有出现。本题是忽略空格、字符、大小写的约束,来判断一句话的内容是否是回文。通过对字符串从两端进行扫描,如果有字母就进行比较,如果不是将该字符忽略找到下一个字符。本题的思路使我们联想起折半查找方法。

提交的代码:

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),在线性的时间内完成了回文的搜索。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: