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.
回文结构:形如1221,asdffdsa asa等正序与逆序相同的结构
解释:12*-as8sa21 返回true,因为按题中解释等价于12as8sa21,从前向后读与从后向前读皆相同“” * 也均返回true,因为相当于空串。忽略大小写
思路:转换成大小写,左右两个下标分别从字符串头尾扫描,并跳过非数字与字母,并记录下跳过的非数字与字母数目。如果左右下标对应字符不等,则表明非回文结构。针对只有非数字字母的情况如/*-/,如果左右坐标跳过的总次数是字符串的长度的2倍,则属于这种情况,根据题意,返回true。
class Solution {
public boolean isPalindrome(String s) {
if(s.length()==0) return true;
String ls = s.toLowerCase();
int l = 0;
int r = ls.length()-1;
int count = 0;
while(l<=r){
while(!Character.isLetterOrDigit(ls.charAt(l))){
l++;
count++;
if(l>=ls.length()) break;
}
while(!Character.isLetterOrDigit(ls.charAt(r))){
r--;
count++;
if(r<0) break;
}
if(count==2*ls.length()) return true;
if(ls.charAt(l)!=ls.charAt(r)) return false;
l++;
r--;
}
return true;
}
}
更简洁的写法:可以看看leedcode 这位兄台的答案 https://leetcode.com/problems/valid-palindrome/discuss/
public class Solution {
public boolean isPalindrome(String s) {
String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
String rev = new StringBuffer(actual).reverse().toString();
return actual.equals(rev);
}
}