All problems
0734HardStringDynamic Programming

Folding A Part Code

Tracked in this browser only
Write code

Trains the technique from

LeetCode 87Scramble String

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 press folds a part code by this rule.

  • A code of one character is left alone.
  • A code of two or more characters is cut at one position into two pieces, with neither piece empty. Each of the two pieces is then folded by this same rule. The two folded pieces are finally written down side by side, either in the order they were cut or with the second piece written first.

The press is free to cut wherever it likes and to choose either order, and it makes those two choices again for every piece it folds.

Given source and target, return true when the press can fold source into target, and false when it cannot. Folding never changes how many characters a code has, and the two given codes need not be the same length.

Examples

Example 1

Input
source = "cargo", target = "gorac"
Output
true

Cut `cargo` into `ca` and `rgo`. Folding `ca` and writing its two characters the other way round gives `ac`. Cutting `rgo` into `r` and `go` and writing the second piece first gives `gor`. Writing those two folded pieces with the second first gives `gor` then `ac`, which is `gorac`.

Example 2

Input
source = "swift", target = "sitwf"
Output
false

The two codes are built from the same five characters, but no set of cuts and orders folds the first into the second.

Example 3

Input
source = "weld", target = "welds"
Output
false

Folding leaves the number of characters unchanged, so a code of four characters can never be folded into a code of five.

Constraints

  • 1 <= source.length <= 30
  • 1 <= target.length <= 30
  • source and target consist of lowercase English letters.

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 is_fold(source: str, target: str) -> bool:
Java
public boolean isFold(String source, String target)
September 7
Apply