題目如下:
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),在線性的時間內完成了迴文的搜索。