给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama" 输出: true
示例 2:
输入: "race a car" 输出: false
方法比较简单,就是从前到后一个一个比就行,直接贴代码了:
public boolean isPalindrome(String s) {
if (s.length() <= 1)
return true;
int rear = s.length() -1, front = 0;
char[] target = s.toCharArray();
for ( ; ; ) {
while (front < s.length() && !isValid(target[front])) {
front ++;
} //find the next valid char in "target"
while (rear >= 0 && !isValid(target[rear])) {
rear --;
} //find the next valid char in "target"
if (front < rear && front < s.length() && rear >= 0) {
if (isEqualIgnoreCase(target[rear], target[front])) {
rear --;
front ++;
continue;
} else {
return false;
}
} else {
return true;
}
}
}
//--------------------------------------------------------------------
public boolean isLetter(char c) {
return isLowercase(c) || isUpperCase(c);
}
public boolean isUpperCase(char c) {
return c >= 'A' && c <= 'Z';
}
public boolean isLowercase(char c) {
return c >= 'a' && c <= 'z';
}
public boolean isNumber(char c) {
return c >= '0' && c <= '9';
}
public boolean isValid(char c) {
return isNumber(c) || isLetter(c);
}
public boolean isEqualIgnoreCase(char c1, char c2) {
if (isLowercase(c1))
c1 = (char) (c1 - 'a' + 'A');
if (isLowercase(c2))
c2 = (char) (c2 - 'a' + 'A');
//convert lowercase to uppercase
return c1 == c2;
}
//---------------------------------------------------------------------------------
public boolean isPalindrome0(String s) {
if (s.length() <= 1)
return true;
char[] source = s.toCharArray();
int index = 0;
for (int i = 0 ; i < source.length ; i ++)
if (isValid(source[i]))
source[index ++] = source[i];
//index is the position to be added.
if (index == 0)
return true;
for (int i = 0 ; i < index ; i ++)
if (!isEqualIgnoreCase(source[i], source[index - 1 - i]))
return false;
return true;
}
写了两种方法,第二种,就当我没试过...