A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.
https://leetcode.com/problems/valid-palindrome/
https://leetcode.com/problems/valid-palindrome/
给定一个字符串 s ,验证 s 是否是 回文串 ,只考虑字母和数字字符,可以忽略字母的大小写。 本题中,将空字符串定义为有效的 回文串 。
示例 1: 输入: s = "A man, a plan, a canal: Panama" 输出: true 解释:"amanaplanacanalpanama" 是回文串 示例 2: 输入: s = "race a car" 输出: false 解释:"raceacar" 不是回文串
Constraints·提示:
1 <= s.length <= 2 * 105
字符串 s 由 ASCII 字符组成
https://leetcode.cn/problems/XltzEq/
https://leetcode.cn/problems/XltzEq/
先全部转小写字母(题目要求忽略大小写)然后先去除除了字母和数字的字符,首尾依次比较

- class Solution {
- public static boolean isPalindrome(String s) {
- String s1 = s.toLowerCase().replaceAll("[^a-z|0-9]", "");
- int length = s1.length();
- for (int i = 0; i < length; i++) {
- int j = length - i - 1;
- if(j <= i){
- break;
- }
- char c1 = s1.charAt(i);
- char c2 = s1.charAt(j);
- if (c1 != c2) {
- return false;
- }
- }
- return true;
- }
- }

- 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());
- }
- }

- 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));
- }
- }
- int n = sgood.length();
- int left = 0, right = n - 1;
- while (left < right) {
- if (Character.toLowerCase(sgood.charAt(left)) != Character.toLowerCase(sgood.charAt(right))) {
- return false;
- }
- ++left;
- --right;
- }
- return true;
- }
- }
我的方法看似和官方提供的双指针法很像,但是执行时间和内存消耗都要更多,特别是执行时间 》〉果然没有对比就没有伤害(╯﹏╰)

刚开始我以为是后面比较时我用的String,官方用的StringBuffer,StringBuffer比String遍历快的原因,于是我把我代码中正则匹配后的的字符串赋值给了一个StringBuffer,然后使用该StringBuffer进行遍历,然并卵(-。-; 更慢了。。。

But!当我把正则匹配换成了Character.isLetterOrDigit(),速度蹿蹿的~~

原来字符串的正则匹配这么慢,欢迎知道原因的同学评论区踢我哦☆〜(ゝ。∂)