Python code that uses no extra space than x


  • -2
    O

    I feel this is a bit tricky, because I convert x to a string and I'm not entirely sure I can claim this is no extra space. I'd like to hear others' opinions.

    class Solution:
        # @return a boolean
        def isPalindrome(self, x):
            x = str(x)
            while len(x) > 0:
                if x[0] != x[-1]:
                    return False
                elif len(x) > 2:
                    x = x[1:len(x)-1]
                else:
                    return True
            return True

  • 1
    B

    How about this:

    class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        x = str(x)
        if x == x[::-1]:
            return True
        else:
            return False

  • 0
    D

    Why the unnecessary if condition? Change your last four lines into
    return x == x[::-1]


Log in to reply
 

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