https://leetcode-cn.com/problems/valid-palindrome/

    1. public boolean isPalindrome(String s) {
    2. if (s.length() == 0) {
    3. return true;
    4. }
    5. char[] str = s.toCharArray();
    6. int L = 0;
    7. int R = s.length() - 1;
    8. while (L < R) {
    9. while (L < R && !Character.isLetterOrDigit(str[L])) {
    10. ++L;
    11. }
    12. while (L < R && !Character.isLetterOrDigit(str[R])) {
    13. --R;
    14. }
    15. if (Character.toLowerCase(str[L]) != Character.toLowerCase(str[R])) {
    16. return false;
    17. }
    18. ++L;
    19. --R;
    20. }
    21. return true;
    22. }

    另一个版本,不用Character类

    1. public static boolean isPalindrome(String s) {
    2. if (s == null || s.length() == 0) {
    3. return true;
    4. }
    5. char[] str = s.toCharArray();
    6. int L = 0;
    7. int R = str.length - 1;
    8. while (L < R) {
    9. if (validChar(str[L]) && validChar(str[R])) {
    10. if (!equal(str[L], str[R])) {
    11. return false;
    12. }
    13. L++;
    14. R--;
    15. } else {
    16. L += validChar(str[L]) ? 0 : 1;
    17. R -= validChar(str[R]) ? 0 : 1;
    18. }
    19. }
    20. return true;
    21. }
    22. public static boolean validChar(char c) {
    23. return isLetter(c) || isNumber(c);
    24. }
    25. public static boolean equal(char c1, char c2) {
    26. if (isNumber(c1) || isNumber(c2)) {
    27. return c1 == c2;
    28. }
    29. return (c1 == c2) || (Math.max(c1, c2) - Math.min(c1, c2) == 32);
    30. }
    31. public static boolean isLetter(char c) {
    32. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    33. }
    34. public static boolean isNumber(char c) {
    35. return (c >= '0' && c <= '9');
    36. }