题目描述:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
中文理解:判断给定一个字符串,排除其中的符号、空格等非字母数字的字符,判断剩下的字符构成的字符串是否是回文字符串。
解题思路:首先将字符串转换为小写字符,然后去除所有非字符和数字的字符,比较去除其他字符后的字符串和其反转。
代码(java):
class Solution {
public boolean isPalindrome(String s) {
String lowS=s.toLowerCase();
StringBuffer s1=new StringBuffer();
for(int i=0;i<lowS.length();i++){
if((lowS.charAt(i)<='z' && lowS.charAt(i)>='a') ||(lowS.charAt(i)<='9' && lowS.charAt(i)>='0') ){
s1.append(lowS.charAt(i));
}
}
String s2=s1.toString();
String s3=s1.reverse().toString();
if(s2.equals(s3))return true;
else return false;
}
}