Find the palindrome
Limits: 2 sec., 256 MiB
This statement was translated automatically from Ukrainian.
Even newborns know that a palindrome is a string of letters that
reads the same way from left to right and from right to left. For
example, the words madam, anna, and
racecar are palindromes, while the words
elephant and penguin are not.
Zenyk is given a string \(s\) consisting of \(n\) lowercase English letters.
Your task is to help him calculate the length of the longest substring that is a palindrome.
Input
The first line contains a single integer \(n\) — the length of the string.
The second line contains the string \(s\), which consists of \(n\) lowercase English letters.
Output
In a single line, output one integer — the length of the longest substring of the string \(s\) that is a palindrome.
Constraints
\(1 \le n \le 7 \cdot 10^3\).
Samples
| Input (stdin) | Output (stdout) |
|---|---|
| 4 anna | 4 |
| Input (stdin) | Output (stdout) |
|---|---|
| 6 banana | 5 |
| Input (stdin) | Output (stdout) |
|---|---|
| 16 thisracecarisred | 7 |
| Input (stdin) | Output (stdout) |
|---|---|
| 10 palindrome | 1 |
Submit a solution
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|
Find the palindrome - Editorial
A palindrome of odd length has a central character. We go over it. Initially the current palindrome consists of one character. We extend the current palindrome in both directions while the character to its left equals the character to its right, and update the answer with the length of the current palindrome.
A palindrome of even length has two equal central characters instead of one. This case is handled the same way.
Complexity: \(O(n^2)\).
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|