Solution 1

 avatar
unknown
python
3 years ago
1.1 kB
9
Indexable
class Solution:
    def validPalindrome(self, s: str) -> bool:
        lp = 0              #starts at beginning of string
        rp = len(s) - 1     #starts at end of string
        while lp < rp:      #while end of string index > beginning of string index
            if s[lp] == s[rp]: #advance index, palindrome!
                lp += 1
                rp -= 1
            else:           #palindrome encountered different letter
                cand_s = s[:lp] + s[lp+1:]  #skips letter on the left pointer side ('abca' skips b)
                if self.is_pal(cand_s):
                    return True
                cand_s = s[:rp] + s[rp+1:]  #skips letter on the right pointer side ('abca' skips c)
                if self.is_pal(cand_s):
                    return True
                return False
        return True                              #assuming no letter differences were encountered, just return True
    def is_pal(self, s: str) -> bool:
        revS = s[::-1]                      #reverses string
        if s == revS:                       #checks if palindrome
            return True
        return False
Editor is loading...