Java recursive solution


  • 0
    public boolean validPalindrome(String s) {
        if (s == null || s.length() == 0 ) return false;
        int i = 0; 
        int j = s.length() - 1;
        boolean deleted = false;
        while (i < j) {
            if (s.charAt(i) == s.charAt(j)) {
                i++;
                j--;
            }
            else {
                if (deleted) return false;
                else return isPalindrome(s, i, j - 1) || isPalindrome(s, i+1, j);
            }
        }
        return true;
    }
    private boolean isPalindrome(String s, int i, int j) {
        while (i < j ) {
            if (s.charAt(i++) != s.charAt(j--)) return false;
        }
        return true;
    }

Log in to reply
 

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