Valid Palindrome

时间:2025-02-28 22:04:20

leetcode:https://oj.leetcode.com/problems/

今天A了一个Easy类型的,主要是判断一个字符串是否是回文。东平西凑的还是给弄好了,具体可看下面的要求,或者直接去网站上看也行

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.

 public class Solution {
public boolean isPalindrome(String str){
char array[] = str.toCharArray();
int i = 0;
int j = array.length - 1;
boolean isPal = true;
if(str.length() == 0)
return true;
else if(str.length() == 1)
return true;
while(i <= j){
while(!isNumOrAlp(array[i++]) && i < array.length);
while(!isNumOrAlp(array[j--]) && j >= 0);
i--;
j++;
if(!isEqual(array[i], array[j]))
{
isPal = false;
break;
}
i++;
j--;
}
if(isPal)
return true; else
return false; }
public boolean isNumOrAlp(char ch){
if(ch >= '0' && ch <= '9')
return true;
else if(ch >= 'a' && ch <= 'z')
return true;
else if(ch >= 'A' && ch <= 'Z')
return true;
else
return false;
}
public boolean isEqual(char ch1,char ch2){
if(0 == ch1 - ch2)
return true;
else if(32 == Math.abs(ch2 - ch1))
return true;
else if(!isNumOrAlp(ch1) && !isNumOrAlp(ch2)){
return true;
}
else
return false;
}
}

这个还是比较简单的,所以就没注释了。很多细节的地方需要注意,oj系统给出错误信息都能很好定位问题在哪儿