描述
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
解题思路
- 把字符串出去非字母数字后,翻转,判断两个字符串是否相等
- 把字符串用双指针再原地判断是否相等(遇到非字母数字移动指针)
思路二代码如下
class Solution {
public boolean isPalindrome(String s) {
String lowCase = s.toLowerCase();
int start = 0;
int end = lowCase.length() - 1;
while (start < end) {
while (start<end&&!Character.isLetterOrDigit(lowCase.charAt(start)))
start++;
while (start<end&&!Character.isLetterOrDigit(lowCase.charAt(end)))
end--;
if (start < end) {
if (lowCase.charAt(start) != lowCase.charAt(end)) {
return false;
}
++start;
--end;
}
}
return true;
}
}
运行结果:
16:35 info
解答成功:
执行耗时:4 ms,击败了64.18% 的Java用户
内存消耗:38.4 MB,击败了82.92% 的Java用户
题解
方法一:筛选 + 判断
class Solution {
public boolean isPalindrome(String s) {
StringBuffer sgood = new StringBuffer();
int length = s.length();
for (int i = 0; i < length; i++) {
char ch = s.charAt(i);
if (Character.isLetterOrDigit(ch)) {
sgood.append(Character.toLowerCase(ch));
}
}
StringBuffer sgood_rev = new StringBuffer(sgood).reverse();
return sgood.toString().equals(sgood_rev.toString());
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法二:在原字符串上直接判断
class Solution {
public boolean isPalindrome(String s) {
int n = s.length();
int left = 0, right = n - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
++left;
}
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
--right;
}
if (left < right) {
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
++left;
--right;
}
}
return true;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
小结
熟悉API,提高解题速度