Valid Palindrome II

String Simulation/Two Pointer

Problem

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

For example:

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

Thought Process

Solution

class Solution:
    def validPalindrome(self, s: str) -> bool:
        
        def isPalindrome(s,l,r):
            while l < r:
                if s[l] != s[r]:
                    return False
                l+=1
                r-=1
            return True
        
        l = 0
        r = len(s)-1
        
        while l < r:
            if s[l] != s[r]:
                return isPalindrome(s, l+1, r) or isPalindrome(s, l, r-1)
            l += 1
            r -= 1
        return True

Last updated

Was this helpful?