iven 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.
Subscribe to see which companies asked this question.
Have you met this question in a real interview?
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
public boolean isPalindrome(String s) {
boolean flag=false;
//if(s==""||"".equals(s.trim())||" ".equals(s.trim())||s==" ")
if( "".equals(s.trim()) || s.length() == 0)
{
flag=true;
}
//过滤字符
String num = s.replaceAll("[^0-9a-zA-Z]","");
System.out.println(num);
String test=num.toLowerCase();//结果存放
// System.out.println(test);
char[] old=test.toCharArray();//转换为字符
//String test2="";
StringBuilder test2=new StringBuilder();
//去掉空格
for(int i=old.length-1;i>=0;i--){
//test2=test2+old[i];
test2.append(old[i]);
}
/* for (char c :
test.toCharArray()) {
test2=test2+c;
}*/
//String test2 = new StringBuilder(test).reverse().toString()
//test2 = new StringBuffer(test).reverse().toString();
System.out.println("反转后:"+test2);
//计算出str与sb中对应位置字符相同的个数n
int n=0;
if(test.equals(test2.toString())){
flag = true;
}else {
flag = false;
}
/* for(int i=0;i<test.length();i++){
if(test.charAt(i)==test2.charAt(i) )
n++;
}
//如果所有字符都相等,即n的值等于str的长度,则str就是回文。
if(n==test.length()){
flag=true;
}*/
return flag;
}
}