A possible implementation is given below as a reference. As mentioned in the other answer, slicing a string creates a copy, which is quite an expensive operation. One way to further improve this algorithm, is to workThis implementation works with indices and pass a reference to s around, instead of creating slices ofstring slicing s all(see the timeother answer) to further speedup the algorithm.
class Solution:
def countCommonStartingCharscount_palindromic_chars(self, s1s: str, s2idx: strint, even_length: bool) -> int:
""" Returns the number of commonpalindromic characters in s at theposition startidx of"""
s1 and s2 """
len_s = len(s)
chars_countershift = 0
# Keep going until the string's end and characters are still palindrome
while (chars_counteridx <- min(len(s1),shift len(s2))>= 0 and idx + shift + even_length < len_s and
s1[chars_counter]s[idx - shift] == s2[chars_counter]s[idx + shift + even_length]):
chars_countershift += 1
return chars_countershift
def longestPalindromelongest_palindrome(self, s: str) -> str:
""" Returns the first longest palindrome substring of s """
longest = ''
for n in range(0, len(s)):
# split after nth char / palindromes of even length
length = self.countCommonStartingCharscount_palindromic_chars(s[n::-1]s, s[n+1:]n, True)
if 2 * length > len(longest):
longest = s[n-length+1:n+length+1]
# split at nth char / palindromes of odd length
length = self.countCommonStartingCharscount_palindromic_chars(s[n::-1]s, s[n:]n, False)
if 2 * length - 1 > len(longest):
longest = s[n-length+1:n+length]
return longest
testsuite = {
# palindromes with odd length
'abcdcth': 'cdc',
'abacdfg': 'aba',
'abcdefe': 'efe',
# palindromes with even length
'abbacdefg': 'abba',
'abcdeffedcklm': 'cdeffedc',
# even length; entire string is palindrome
'abcddcba': 'abcddcba',
# all the same characters
'a': 'a',
'aa': 'aa',
'aaa': 'aaa',
'aaaa': 'aaaa',
# start with different character than all the same characters
'ba': 'b', # first palindrome is 'b', not 'a'
'baa': 'aa',
'baaa': 'aaa',
'baaaa': 'aaaa',
# all the same characters and end with different character
'aab': 'aa',
'aaab': 'aaa',
# palindrome of length 1
'abcdef': 'a',
# two palindromes in one string (last one longer)
'abcbdefghhgfekl': 'efghhgfe',
'abcbdefedh': 'defed'
}
s = Solution()
for case, result in testsuite.items():
observed = s.longestPalindromelongest_palindrome(case)
print(f"{case} -> {observed}; "
f"this is{' NOT' if observed != result else ''} correct")