# Valid Palindrome @LeetCode

package Level2;

/**
* Valid Palindrome
*
* 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 class S125 {

public static void main(String[] args) {
String s = ".;.;..;{,";
System.out.println(isPalindrome(s));
}

// 原来递归对于太长字符串会StackOverflow!改成迭代通过
public static boolean isPalindrome(String s) {
if(s==null || s.length()==0 || s.length()==1){
return true;
}
int i = 0, j = s.length()-1;

while(i <= j){
// Java中用Character.isLetterOrDigit 来检查是否是alphanumeric
while(i<s.length() && !Character.isLetterOrDigit(s.charAt(i))){
i++;
}
while(j>=0 && !Character.isLetterOrDigit(s.charAt(j))){
j--;
}
// 注意检查可能已经越界的问题！
if(i<s.length() && j>=0 && Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))){
return false;
}
i++;
j--;
}

return true;
}

}


• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 1
评论
05-06 4219
09-20 5万+
06-08 3万+
03-10 2万+
09-18 7486
06-24 2万+
07-31 5万+
04-22 1575
01-03 111

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。