目录
题目
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
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.
解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class Solution { public boolean isPalindrome(String s) { int len = s.length(); if(s == null || s.length() == 0) return true; StringBuilder builder1 = new StringBuilder(); StringBuilder builder2 = new StringBuilder(); s = s.toLowerCase(); boolean result = true; for(int i = 0; i < len; i++){ if(isDigitOrLetter(s.charAt(i))){ builder1.append(s.charAt(i)); } } for(int j = len-1 ; j >= 0; j--){ if(isDigitOrLetter(s.charAt(j))){ builder2.append(s.charAt(j)); } } for(int k = 0; k < builder1.length(); k++){ if(builder1.charAt(k) != builder2.charAt(k)){ result = false; break; } } return result; } private static boolean isDigitOrLetter(char s){ if((s >= 'a' && s <= 'z') || (s >= 'A' && s <= 'Z') ||(s >= '0' && s <= '9')){ return true; } else { return false; } } }
|
注意事项
- 先处理特殊情况,字符串为空或者长度为零。
- 定义一个函数isDigitOrLetter()来判断某个字符是否是字母大小写+数字。
- 使用两个StringBuilder,分别从首尾遍历字符串,存储为字母大小写+数字的字符。
- 比较两个StringBuilder中内容是否一样即可。