题目:
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.
思路:先将字符串中的字母跟数字按顺序提取出来放到一个新的字符串中,再用while循环比较新的字符串相对应位置的字符是否相等。若出现不相等的情况则返回false,循环完毕都没有返回FALSE,则是回文字符串。
注意:比较的时候是忽略大小写的。
public class Solution2 {
public boolean isPalindrome(String s) {
StringBuffer sb = new StringBuffer();
for(int i=0;i<s.length();i++){
if(Character.isDigit(s.charAt(i)) || Character.isLetter(s.charAt(i))){
System.out.println(s.charAt(i));
sb.append(s.charAt(i));
}
}
String str = sb.toString();
System.out.println(str);
int j = 0;
int k = str.length()-1;
boolean isPalindrome = true;
while(j<=k){
if(Character.toUpperCase(str.charAt(j)) == Character.toUpperCase(str.charAt(k))){
j++;
k--;
}else{
return false;
}
}
return isPalindrome;
}
public static void main(String[] args) {
Solution2 s2 = new Solution2();
System.out.println(s2.isPalindrome("`l;`` 1o1 ??;l`"));
}
}
结果输出true.