Python easy and concise solution

  • 5
    def validPalindrome(self, s):
            i = 0
            while i < len(s) / 2 and s[i] == s[-(i + 1)]: i += 1
            s = s[i:len(s) - i]
            return s[1:] == s[1:][::-1] or s[:-1] == s[:-1][::-1]

  • 1

    @lee215 said in Python easy and concise solution:

    s[-(i + 1)]

    Nice solution.

    But I think the code can be nicer if you use ~i to replace -(i + 1)

    And you don't have to reverse the string. This is more efficient.

    for i in xrange(len(s) / 2)]:
        if s[i] != s[~i]:
            return False
    return True

    or a shorter version, but cannot break early

    all([s[i] == s[~i] for i in xrange(len(s) / 2)])

    The one can break early is:

    all(s[i] == s[~i] for i in xrange(len(s) / 2))

  • 0

    I like the replacement ~i to -(i + 1)
    I reverse the string because it is very clear and efficient enough.

  • 0

    very nice and clean code! Thanks!

  • -1

    @lee215 This solution is not readable at all.

  • 1

    @Learntocode I think it's pretty clear..... Find the first pair when the two characters don't match. Then check without the left character, whether the rest is the same when it's reversed, or without the right character, whether the rest is the same when it's reversed.

Log in to reply

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