807. Fewest Insertions to Mirror
A calligrapher has painted a banner whose letters are the lowercase string s. The banner should be a perfect mirror: it must read the same from the left end as from the right end. She cannot erase or change anything that is already painted, but she may paint new letters in any gaps, including before the first letter and after the last.
Return the minimum number of letters she must add so that the banner becomes a palindrome. A banner that already reads the same both ways needs 0 additions.
Your solution should run in O(n^2) time, where n is the length of s, and use O(n) extra space.
Example 1
- Input:
- s = "ribbonrib"
- Output:
- 5
- Explanation:
The banner "ribbonrib" needs 5 inserted letters before it reads the same from both ends.
Example 2
- Input:
- s = "quartzquake"
- Output:
- 8
- Explanation:
The banner "quartzquake" needs 8 inserted letters before it reads the same from both ends.
Example 3
- Input:
- s = "lamplight"
- Output:
- 6
- Explanation:
The banner "lamplight" needs 6 inserted letters before it reads the same from both ends.
Constraints
1 ≤ s.length ≤ 1200
s contains only lowercase English letters.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n^2)
- Space
- O(n)