Valid Palindrome II

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'.

    bool isPalindromeUtil(string &s, int l, int r, bool &hasDeleted) {
        if (l == r) return true;
        while (l < r) {
            while (l < r && !isalnum(s[l])) l++;
            while (l < r && !isalnum(s[r])) r++;
            if (s[l] != s[r]) {
                if (hasDeleted) return false;
                hasDeleted = true;
                return isPalindromeUtil(s, l+1, r, hasDeleted) || isPalindromeUtil(s, l, r-1, hasDeleted);
            }
            l++; r--;
        }
        return true;
    }

    bool validPalindrome(string s) {
        if (s.empty()) return true;
        bool hasDeleted = false;
        return isPalindromeUtil(s, 0, (int)s.size()-1, hasDeleted);
    }

Solution: Greedy

bool isPalindromeUtil(string s, int i, int j) {
    while (i < j) {
        if (s[i] != s[j]) return false;
        i++; j--;
    }
    return true;
}

bool validPalindrome(string s) {
    int i = 0, j = (int)s.size()-1;
    while (i < j) {
        if (s[i] != s[j]) {
            return isPalindromeUtil(s, i+1, j) || isPalindromeUtil(s, i, j-1);
        }
        i++; j--;
    }
    return true;
}

results matching ""

    No results matching ""