题目描述
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
给定一个字符串(可能含有各种元素),只看其中的字母和数字,判断是否是回文字符串。
字符串为空也算回文串,忽略字母的大小写。
解题思路
思路很清晰:
- 先统一字母的大小写;
- 再从这些字符串中取出字母和数字,存放到一个集合list里;
(为什么统一大小写在这一步前面呢?因为第二步我使用了list,转换字母的大小写用数组操作比较方便); - 最后分别从头和尾向中间逼近,逐个比较头尾元素是否相等。
实现代码
根据上述思路可得Java代码:.
public boolean isPalindrome(String s) {
char[] c=s.toCharArray(); //字符串转换成字符数组
ArrayList<Character> list=new ArrayList<>(); //list用来存放最终得出的全为小写的字母和数字
//如果是大写字母,转换成小写字母
for(int i=0;i<c.length;i++) {
if(c[i]>='A' && c[i]<='Z') {
c[i]+=32;
}
}
//选取出字母和数字,装入list
for(int i=0;i<c.length;i++) {
if((c[i]>='a' && c[i]<='z') || (c[i]>='0' && c[i]<='9')) {
list.add(c[i]);
}
}
//首尾逐渐逼近进行比较
int low=0;
int high=list.size()-1;
while(low<high) {
if(!(list.get(low).equals(list.get(high)))) {
return false;
}
low++;
high--;
}
return true;
}