题目原型:
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; for (int i = 0, j = s.length() - 1; i < j;) { char ch1 = s.charAt(i); char ch2 = s.charAt(j); //假如所得字符不在A-Z并且不在a-z也不在0-9或者为空 while(!(ch1>=‘A‘&&ch1<=‘Z‘)&&!(ch1>=‘a‘&&ch1<=‘z‘)&&!(ch1>=‘0‘&&ch1<=‘9‘)||ch1==‘ ‘) { i++; if(i<j) ch1 = s.charAt(i); else return true; } while(!(ch2>=‘A‘&&ch2<=‘Z‘)&&!(ch2>=‘a‘&&ch2<=‘z‘)&&!(ch2>=‘0‘&&ch2<=‘9‘)||ch2==‘ ‘) { j--; if(i<j) ch2 = s.charAt(j); else return true; } //比较时忽略大小写 String s1 = s.substring(i,i+1); String s2 = s.substring(j,j+1); if(!s1.equalsIgnoreCase(s2)) return false; else { i++; j--; } } return true; }
Valid Palindrome,布布扣,bubuko.com
原文:http://blog.csdn.net/cow__sky/article/details/21818403