LeetCode算法面试题汇总
验证回文串
这题我想的有点复杂,利用到了正则表达式replaceAll()来实现这么一个过程
class Solution {
public boolean isPalindrome(String s) {
if(s=="") return true;
String temp = s.toLowerCase();
String reg = "[^0-9a-zA-Z]";
String str=temp.replaceAll(reg,"");
int length=str.length()-1;
boolean flag=true;
int i=0;
while(length-i>=i) {
if (str.charAt(i)==str.charAt(length - i++)){
continue;
}
else {
return false;
}
}
return true;
}
}
但是别人就很直接了,while()得到一个数字或者字母,然后判断这两个是否相同。
class Solution {
//首尾指针,同步走,遇到非数字或字母就跳过,一一比较
public boolean isPalindrome(String s) {
if(s == null)
return true;
int left = 0;
int right = s.length() - 1;
char[] arr = s.toCharArray();
while(left < right){
while(left < right && !isLetterOrDigit(arr[left]))
left++;
while(left < right && !isLetterOrDigit(arr[right]))
right--;
if(toLowCase(arr[left]) == toLowCase(arr[right])){
left++;
right--;
}
else
return false;
}
return true;
}
public boolean isLetterOrDigit(char c) {
if (('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')) {
return true;
}
return false;
}
public char toLowCase(char c) {
if ('A' <= c && c <= 'Z') {
return (char)(c + 32);
}
return c;
}
}