双指针解法1:
public final boolean isPalindrome(String s) { int length = s.length(); int leftPoint = 0; int rightPoint = length - 1; s = s.replaceAll("[\pP‘’“”``]", " "); while (leftPoint < rightPoint) { char leftChar = s.charAt(leftPoint); while (leftPoint < rightPoint && leftChar == ' ') { leftPoint++; leftChar = s.charAt(leftPoint); } char rightChar = s.charAt(rightPoint); while (leftPoint < rightPoint && rightChar == ' ') { rightPoint--; rightChar = s.charAt(rightPoint); } if (leftPoint < rightPoint) { leftChar = Character.toLowerCase(leftChar); rightChar = Character.toLowerCase(rightChar); if (leftChar != rightChar) { return false; } leftPoint++; rightPoint--; } } return true; }
双指针解法2:
public boolean isPalindrome0(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; }
两个解法都是双指针,区别在于方法 1 使用正则表达式一次性过滤了所有符号字符;而方法二通过 Character.isLetterOrDigit 方法逐个判断每个字符是不是标点。
方法二为懒处理,遇到了才处理,对于可能在任何位置直接返回 false 的函数来说,综合开销小于方法 1 。