All problems
0084MediumTwo PointersStringDynamic Programming

Reversible Tape Stretches

Tracked in this browser only
Write code

Trains the technique from

LeetCode 647Palindromic Substrings

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A label printer has run off a tape of lowercase letters, handed to you as the string tape. Quality control wants to know how much of the tape reads the same whichever way you feed it into the reader.

A stretch is one or more neighbouring letters of the tape, pinned down by where it starts and where it ends. A stretch is reversible when its letters spell out the same thing read right to left as they do read left to right. A stretch of a single letter is reversible.

Return how many reversible stretches the tape holds. Stretches that cover different positions count separately, even when they spell the same letters, so the tape "dd" holds three: each d on its own, plus the pair.

Examples

Example 1

Input
tape = "dvd"
Output
4

The three single letters are reversible, and so is the whole tape.

Example 2

Input
tape = "pqqp"
Output
6

Four single letters, then `qq`, then the whole tape, and nothing else reads the same both ways.

Example 3

Input
tape = "wxyz"
Output
4

No two neighbouring letters match, so only the four single letters are reversible.

Constraints

  • 1 <= tape.length <= 1000
  • tape holds lowercase English letters only

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def count_reversible_stretches(tape: str) -> int:
Java
public int countReversibleStretches(String tape)
September 7
Apply