[leetCode]125.验证回文串
筛选+反转
回文串将其反转之和还是它本身。先将字母和数字筛选出来放入StringBuffer中,再进行反转判断。
class Solution {
public boolean isPalindrome(String s) {
int len = s.length();
if(len == 0) return true;
StringBuffer sgood = new StringBuffer();
for(int i = 0; i < len; i++){
if(Character.isLetterOrDigit(s.charAt(i))){
sgood.append(Character.toLowerCase(s.charAt(i)));
}
}
StringBuffer sgood_rev = new StringBuffer(sgood).reverse();
return sgood.toString().equals(sgood_rev.toString());
}
}
双指针
定义两个指针,跳过非数字和字母,一个向右移动一个向左移动,如果所指向的字符不等则不是回文串,如果指针相遇循环结束则是回文串。
class Solution {
public boolean isPalindrome(String s) {
int len = s.length();
if(len == 0) return true;
s = s.toLowerCase();
int lo = 0, hi = len - 1;
//不能跳过数字
while(lo < len && (s.charAt(lo) <'a' || s.charAt(lo) > 'z') && (s.charAt(lo) <'0' || s.charAt(lo) > '9')){
lo++;
}
while(hi > 0 && (s.charAt(hi) <'a' || s.charAt(hi) > 'z') && (s.charAt(hi) <'0' || s.charAt(hi) > '9')){
hi--;
}
while(lo<=hi) {
if(s.charAt(lo) == s.charAt(hi)){
lo++;
while(lo < len && (s.charAt(lo) <'a' || s.charAt(lo) > 'z') && (s.charAt(lo) <'0' || s.charAt(lo) > '9')){
lo++;
}
hi--;
while(hi > 0 && (s.charAt(hi) <'a' || s.charAt(hi) > 'z') && (s.charAt(hi) <'0' || s.charAt(hi) > '9')){
hi--;
}
}else{
return false;
}
}
return true;
}
}
把上面的代码优化一下
class Solution {
public boolean isPalindrome(String s) {
int len = s.length();
if(len == 0) return true;
s = s.toLowerCase();
int lo = 0, hi = len - 1;
while(lo < hi) {
while(lo < hi && !Character.isLetterOrDigit(s.charAt(hi))){
hi--;
}
while(lo < hi && !Character.isLetterOrDigit(s.charAt(lo))){
lo++;
}
if(s.charAt(lo) != s.charAt(hi))
return false;
lo++;
hi--;
}
return true;
}
}