Description
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
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.
Example
"A man, a plan, a canal: Panama"
is a palindrome.
"race a car"
is not a palindrome.
Challenge
O(n) time without extra memory.
解题:判断某字符串是否是回文字符串,其中标点可以不对称,但字母和数字必须要对称。可以通过Character中的函数, isLetterOrDigit( char ch )来判断。代码如下:
public class Solution {
/**
* @param s: A string
* @return: Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
// write your code here
s = s.toUpperCase();
for(int i = 0, j = s.length() - 1; i <= j; i++, j--){
if(s.charAt(i) == s.charAt(j))
continue;
else{
if(Character.isLetterOrDigit(s.charAt(i)) && Character.isLetterOrDigit(s.charAt(j)))
return false;
else{
if(Character.isLetterOrDigit(s.charAt(i))){
i--;
}else if(Character.isLetterOrDigit(s.charAt(j))){
j--;
}else{
continue;
}
}
}
}
return true;
}
}