Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
题意
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。说明:本题中,我们将空字符串定义为有效的回文串。样例
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
解题
首先字符串中多余的字符不在考虑的范围之类,而如果字符串是回文串,我们就可以设置双指针,使用双指针法,一头一尾判断字符是否相等,若存在不相等时输出false。代码如下:
public boolean isPalindrome(String s) {if (s.isEmpty())return true;
int begin = 0;
int end = s.length() - 1;
char beginChar, endChar;while (begin <= end){
beginChar = s.charAt(begin);
endChar = s.charAt(end);if (!Character.isLetterOrDigit(beginChar)){begin++;
continue;
}else if (!Character.isLetterOrDigit(endChar)){end--;
continue;
}else {if (Character.toLowerCase(beginChar) != Character.toLowerCase(endChar))return false;else{begin++;end--;
}
}
}return true;
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。上期推文:LeetCode1-120题汇总,希望对你有点帮助!LeetCode刷题实战121:买卖股票的最佳时机LeetCode刷题实战122:买卖股票的最佳时机 IILeetCode刷题实战123:买卖股票的最佳时机 IIILeetCode刷题实战124:二叉树中的最大路径和