目录结构
1.题目
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例:
输入: "A man, a plan, a canal: Panama"
输出: true
输入: "race a car"
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
- 通过正则去掉除字母和数字外的其他字符;
- 通过toLowerCase()将字母转为小写;
- 双指针一前一后遍历对比。
public class Solution125 {
public boolean isPalindrome(String s) {
s = s.replaceAll("[^0-9a-zA-Z]", "");
s = s.toLowerCase();
for (int i = 0, j = s.length() - 1; i <= j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}
下面代码本质一样,只是将正则处理部分改为了代码跳过非数字和字母,提高运行速度。
public class Solution125 {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
for (int i = 0, j = s.length() - 1; i <= j; ) {
if (!Character.isDigit(s.charAt(i)) && !Character.isLetter(s.charAt(i))) {
i++;
continue;
}
if (!Character.isDigit(s.charAt(j)) && !Character.isLetter(s.charAt(j))) {
j--;
continue;
}
if (s.charAt(i) != s.charAt(j)) {
return false;
} else {
i++;
j--;
}
}
return true;
}
}
- 时间复杂度:
- 空间复杂度: