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
算法思路:总的来说这道题还是比较简单的,首先动态创建两个StringBuffer两个类,然后把String的内容按照数字字母(把大写变成小写,小写不变)通过用append()方法分别加入到StringBuffer sb ,StringBuffer str 中,然后利用reverse()方法反转sb,然后通过toString()把StringBuffer类变成String类,最后用equals()对 sb 和 str 进行比较,如果相等就是回文,返回 true,如果不相等返回false。
注意:1.要想用equals 进行字符串比较,首先把StringBuffer变成Sting,用toString()方法
2.把sb 反转后 也就是说sb.reverse = sb,他们都是反转过后的字符串,所以相等。
最后附上自己的代码
class Solution {
public boolean isPalindrome(String s) {
if(s.length() == 0 || s.length() == 1) return true;
StringBuffer sb = new StringBuffer();
StringBuffer str = new StringBuffer();
char [] ch = s.toCharArray();
for(int i = 0; i < ch.length; i++){
if((ch[i] >= 97 && ch[i] <= 122) || (ch[i] >= 48 && ch[i] <= 57)){
sb.append(ch[i]);
str.append(ch[i]);
}
else if(ch[i] >= 65 && ch[i] <= 90){
sb.append(Character.toLowerCase(ch[i]));
str.append(Character.toLowerCase(ch[i]));
}
}
if(str.reverse().toString().equals(sb.toString())) return true;//注意细节
else return false;
}
}