Online store~20 min2s · 256 MBtarget O(n^2) time, O(1) spaceclassic twin: lc-5string-algorithms
A shop-naming tool builds logos from shop names. It looks for the longest stretch of the name that reads the same forwards and backwards, such as "anana" in "bananas", and draws it as a mirrored badge.
Names are short, at most a thousand characters. You build the function that finds the stretch.
Write longest_palindrome(name).
name.Input: name = "bananas"
Output: "anana"A stretch grows outwards from a centre for as long as its two ends match.
| Centre | Longest stretch around it | Length |
|---|---|---|
| letter n (index 2) | ana | 3 |
| letter a (index 3) | anana | 5 |
| letter n (index 4) | ana | 3 |
The stretch anana is five characters long. No longer stretch reads the same both ways. The table lists the centres that give stretches of two or more characters.
Input: name = "cbbd"
Output: "bb"The only stretch of two or more characters is bb.
Input: name = "xy"
Output: "x"Both stretches have length 1, so the one that starts first wins.
1 ≤ name.length ≤ 1,000Testing every stretch costs about n³ / 6 character comparisons at worst, about 1.7 × 10^8 at n = 1,000. Growing a stretch outwards from each of the 2n - 1 centres costs about n² / 2 steps, 5 × 10^5 at the same size. Every mirrored stretch has a centre, so no stretch is missed.