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]
s[-(i + 1)]
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))
I like the replacement
~i to -(i + 1)
I reverse the string because it is very clear and efficient enough.
@lee215 This solution is not readable at all.
@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.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.