AC JAVA Solution using pointers.


  • -1
    J

    Using pointers to store the index of which the palindrome condition is violated for the first time. Then try skipping the left char and keep checking. If palindrome condition violated again, move pointer back to the stored locations and try skipping the right char. If either works, return true.

    class Solution {
        public boolean validPalindrome(String s) {
            if (s == null || s.length() <= 1) return true;
            int left = 0; int right = s.length() - 1;
            int tempL = -1; int tempR = s.length();
            while (left < right) {
                if (s.charAt(left) == s.charAt(right)) {
                    left++; right--;
                }
                
                else if (tempL != -1 && tempR != s.length()) {
                    return false;
                }
                else if (tempL == -1) {
                    tempL = left;
                    left++;
                }
                else {
                    left = tempL;
                    tempR = s.length() - 1 - left;
                    right = tempR - 1;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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