Expert · Dynamic programming · 218 of 264
Longest palindrome inside
Find the longest part of a text (consecutive characters) that is a palindrome. If several are equally long, print the one that starts first. Texts have up to 2000 characters.
Input: one line. Output: the palindrome.
Examples
Input
babad
Output
bab
Input
cbbd
Output
bb
Input
x
Output
x
2 more tests check other inputs when you press Check.
Stuck? The idea behind dynamic programming
Break the problem into smaller ones that repeat, and keep each answer in a table so it is worked out only once.
Decide what one cell of the table means ("the best total using the first i items"), how it follows from earlier cells, and where it starts.
n = 10
ways = [0] * (n + 1)
ways[0] = 1
for i in range(1, n + 1):
ways[i] = ways[i - 1] + (ways[i - 2] if i >= 2 else 0)
print(ways[n]) # climbing 10 stairs, 1 or 2 at a timeWatch for: Fill the table in an order where every cell it needs is already filled.