Merge by Longest Overlap
MediumStrings · Apple
Given two lowercase strings first and second, merge them into one string by overlapping the end of one with the start of the other.
The overlap of x before y is the largest k (from 0 to the length of the shorter string) such that the last k letters of x equal the first k letters of y. Merging x before y gives x followed by y without its first k letters.
Try both orders and return the merge with the larger overlap. If the overlaps are equal, return first before second.
Example 1
- Input:
- first = "sunrise", second = "risen"
- Output:
- "sunrisen"
- Explanation
- The last 4 letters of
sunriseequal the first 4 ofrisen, so only the finalnis added. The other order overlaps by 0.
Example 2
- Input:
- first = "lantern", second = "ernlan"
- Output:
- "lanternlan"
- Explanation
- Both orders overlap by 3 letters, so
firstgoes beforesecond.
Example 3
- Input:
- first = "net", second = "planet"
- Output:
- "planet"
Constraints
- 1 ≤
first.length ≤ 10000 - 1 ≤
second.length ≤ 10000 firstandsecondconsist of lowercase English letters