class Solution(object): def longestPalindrome(self, s): start = maxlen = 0 for i in range(len(s)): for k in (0, 1): _start, _maxlen = self.build(s, i-k, i+1) if _maxlen > maxlen: maxlen, start = _maxlen, _start return s[start:start+maxlen] def build(self, s, m, n): length = len(s) while m >= 0 and n < length and s[m] == s[n]: m -= 1 n += 1 return m+1, n-m-1
@wonderfuly Thanks for your nice code! It enlightens me but I found a 'mistake' in " for i, c in enumerate(s): " . 'c' doesn't appear in any other palces. May " for i, _ in enumerate(s): " would be better?
@Lovingmylove or we can change it to
for i in range(len(s)):
@wonderfuly As far as I can see, for i in range(len(s)) is not a good choice. Maybe you can use xrange() to replace range(), because xrange() produce a value one time when you call it with no need for larger storage space. So I think xrange() is better than range(). What's more, len(s) is not suitable to write as range(len(s)). Out of the loop may be better.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.