Clean Java solution beats 93%


  • 0

    use a isP() function to help.
    skip the character when not the same.
    I get this AC for 35ms.

    class Solution {
        public boolean validPalindrome(String s) {
            char[] arr = s.toCharArray();
            if (isP(arr, 0, arr.length - 1)) {return true;}
            int i = 0, j = s.length() - 1;
            while (i < j) {
                if (arr[i] != arr[j]) {
                    // when the character are different, skip one to check if the rest is Palindrom
                    return isP(arr, i + 1, j) || isP(arr, i, j - 1);
                }
                i++; j--;
            }
            return true;
        }
        
        public boolean isP(char[] arr, int i, int j) {
            while (i < j) {
                if (arr[i] != arr[j]) {return false;}
                i++; j--;
            }
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.