我们将空字符串判定为有效回文。
public class Solution {
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
// Write your code here、
if(s == null || s.length()==0 || s.length()==1){
//有一个字符就是回文串
return true;
}
int i = 0;
int j = s.length() - 1;
while(i<j){
while(i < s.length() && isnotValid(s.charAt(i))){
i+=1;
}
if(i==s.length()){//!!!!!!!!!!!!!!!!!!!重要!不然会出现数组越界情况
return true;
}
while(j >= 0 && isnotValid(s.charAt(j))){
j-=1;
}
i+=1;
j-=1;
}else{
return false;
}
}
return true;
}
public boolean isnotValid(char ch){
//可用Character.isLetter(c)||Character.isDigit(c)直接判断是否为有效字符
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||(ch>='0'&&ch<='9'))
return false;
return true;
}
}
"A man, a plan, a canal: Panama"
是一个回文。
"race a car"
不是一个回文。
public class Solution {
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
// Write your code here、
if(s == null || s.length()==0 || s.length()==1){
//有一个字符就是回文串
return true;
}
int i = 0;
int j = s.length() - 1;
while(i<j){
while(i < s.length() && isnotValid(s.charAt(i))){
i+=1;
}
if(i==s.length()){//!!!!!!!!!!!!!!!!!!!重要!不然会出现数组越界情况
return true;
}
while(j >= 0 && isnotValid(s.charAt(j))){
j-=1;
}
//不要用 !=比较字符串!!!!!!!!
if(String.valueOf(s.charAt(i)).toLowerCase() .equals (String.valueOf(s.charAt(j)).toLowerCase())){i+=1;
j-=1;
}else{
return false;
}
}
return true;
}
public boolean isnotValid(char ch){
//可用Character.isLetter(c)||Character.isDigit(c)直接判断是否为有效字符
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||(ch>='0'&&ch<='9'))
return false;
return true;
}
}