题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/5/strings/36/
题目描述 :
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
思路:先把字母都转换为小写,然后用双指针,一个从开头开始,一个从结尾开始。遇到不符合条件的字符,自加1(开头指针) 或者自减1(结尾指针)。然后再判断两个指针对应的值是否相等。两种方法思路一样。第二种比较节省内存还有比较规范吧。
//自己写的方法。
class Solution {
public boolean isPalindrome(String s) {
int start=0;
int n=0;
s=s.toLowerCase();
char[] ch= new char[s.length()];
for(int i=0;i<s.length();i++){
if(isAlphaNum(s.charAt(i))){
ch[n]=s.charAt(i);
n++;
}
}
int end=n-1;
while(start<end){
if(ch[start]==ch[end]){
start++;
end--;
}else{
return false;
}
}
return true;
}
private boolean isAlphaNum(char c){
if(c >= 'a' && c <= 'z') return true;
if(c >= 'A' && c <= 'Z') return true;
if(c >= '0' && c <= '9') return true;
return false;
}
}
//无需额外空间。直接双指针解决
class Solution {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
int startIndex = 0;
int endIndex = s.length() - 1;
while (startIndex < endIndex && startIndex < s.length() - 1) {
char pre = s.charAt(startIndex);
char aft = s.charAt(endIndex);
if (!((pre >= 'a' && pre <= 'z') || (pre >= '0' && pre <= '9'))) {
startIndex++;
continue;
}
if (!((aft >= 'a' && aft <= 'z') || (aft >= '0' && aft <= '9'))) {
endIndex--;
continue;
}
if (pre != aft) {
return false;
}
startIndex++;
endIndex--;
}
return true;
}
}
//双指针解决。且不需要进行字符串大小写转换。
class Solution {
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while(left < right){
if(!isAlphaNum(s.charAt(left))){
left ++;
}else if(!isAlphaNum(s.charAt(right))){
right --;
}else if((s.charAt(left) + 32 - 'a') % 32 != (s.charAt(right) + 32 - 'a') % 32){
return false;
}else{
left ++;
right --;
}
}
return true;
}
private boolean isAlphaNum(char c){
if(c >= 'a' && c <= 'z') return true;
if(c >= 'A' && c <= 'Z') return true;
if(c >= '0' && c <= '9') return true;
return false;
}
}
反思:刚才重新做了一遍,发现第二种方法的else if((s.charAt(left) + 32 - 'a') % 32 != (s.charAt(right) + 32 - 'a') % 这句很妙。直接能跳过大小写字母的处理。