125. Valid Palindrome
- Total Accepted: 144943
- Total Submissions: 565871
- Difficulty: Easy
- Contributors: Admin
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.
Subscribe to see which companies asked this question.
Show Similar Problems
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
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()))
{
flag=true;
}
//过滤字符
String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(s);
String num=m.replaceAll("").trim();
String test="";//结果存放
char[] old=num.toCharArray();//转换为字符
//去掉空格
for(int i=0;i<old.length;i++){
if(old[i]==' '||" ".equals(old[i])){
continue;
}
else{
test=test+old[i];
}
}
//根据字符串创建一个字符缓存类对象sb
StringBuffer sb=new StringBuffer(test);
//将字符缓存中的内容倒置
sb.reverse();
//计算出str与sb中对应位置字符相同的个数n
int n=0;
test=test.toLowerCase();
String sb2=sb.toString().toLowerCase();
for(int i=0;i<test.length();i++){
if(test.charAt(i)==sb2.charAt(i) )
n++;
}
//如果所有字符都相等,即n的值等于str的长度,则str就是回文。
if(n==test.length()){
flag=true;
}
return flag;
}
}