题目如下:
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),在线性的时间内完成了回文的搜索。