← DiffPush

Longest palindromic substring

Standard Bar Strings · Medium O(n^2) · O(1)

The Loom's Longest Mirror Run

A textile QC scanner reads a fabric's thread pattern as one long string of colour codes and certifies the bolt by pointing at the longest run that reads the same forwards and backwards — the mirror-symmetric motif the designer can feature. Runs of odd and even length hide around different centres, so the scanner treats every position as a potential centre and stretches outward while the colours agree.

Input: A string s.

Output: The longest substring of s that is a palindrome; when several share the maximum length, any one of them is a correct answer (or "" when s is empty).

Constraints

Examples

Example 1

Input: {"s":"babad"}
Output: "bab"
"bab" and "aba" both qualify; the canonical centre-expansion sweep returns the first maximum it meets.

Example 2

Input: {"s":"cbbd"}
Output: "bb"
The even-length palindrome spanning the two middle b's beats every single character.

Solve this in your browser →

Also on LeetCode ↗