Talentd
FleetCode

3455. Shortest Matching Substring

Hard24.5% acceptance1 company

You are given a string s and a pattern string p, where p contains exactly two '*' characters.

The '*' in p matches any sequence of zero or more characters.

Return the length of the shortest substring in s that matches p. If there is no such substring, return -1.

Note: The empty substring is considered valid.

Example 1:

Input: s = "abaacbaecebce", p = "ba*c*ce"

Output: 8

Explanation:

The shortest matching substring of p in s is "baecebce".

Example 2:

Input: s = "baccbaadbc", p = "cc*baa*adb"

Output: -1

Explanation:

There is no matching substring in s.

Example 3:

Input: s = "a", p = "**"

Output: 0

Explanation:

The empty substring is the shortest matching substring.

Example 4:

Input: s = "madlogic", p = "*adlogi*"

Output: 6

Explanation:

The shortest matching substring of p in s is "adlogi".

Constraints:

  • 1 <= s.length <= 105
  • 2 <= p.length <= 105
  • s contains only lowercase English letters.
  • p contains only lowercase English letters and exactly two '*'.

Asked at 1 company

Hints open one at a time

Hint 1
The pattern string p can be divided into three segments.
Hint 2
Use the KMP algorithm to locate all occurrences of each segment in s.
29:10
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def shortestMatchingSubstring(self, s: str, p: str) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
"abaacbaecebce"
"ba*c*ce"
Input
"baccbaadbc"
"cc*baa*adb"
Input
"a"
"**"
Input
"madlogic"
"*adlogi*"
Your code is saved on this device.Solution