Shortest Matching Substring Problem
Description
LeetCode Problem 3455.
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 <= 10^52 <= p.length <= 10^5scontains only lowercase English letters.pcontains only lowercase English letters and exactly two'*'.
Solution
Approach: KMP on Three Pieces
The pattern has exactly two stars, so split it into three literals a, b and c (any of them can be empty). A match is an occurrence of a, followed later by an occurrence of b, followed later by an occurrence of c, with no overlaps, and its length runs from the start of a to the end of c.
Use KMP to list every start position of each literal in s; an empty literal starts at every index 0..n. For each start i of a, the best choice is the earliest start j >= i + |a| of b, then the earliest start k >= j + |b| of c: choosing later positions can only make the match longer. The match length is k + |c| - i. Because i increases, the pointers into the lists for b and c only move forward, so one pass is enough.
The answer is the smallest length found, or -1 if no match exists.
Complexity: O(n + |p|) time and O(n) space.
class Solution:
def shortestMatchingSubstring(self, s: str, p: str) -> int:
def starts(pat: str):
if not pat:
return list(range(len(s) + 1))
m = len(pat)
lps = [0] * m
length = 0
i = 1
while i < m:
if pat[i] == pat[length]:
length += 1
lps[i] = length
i += 1
elif length:
length = lps[length - 1]
else:
i += 1
res = []
i = j = 0
n = len(s)
while i < n:
if s[i] == pat[j]:
i += 1
j += 1
if j == m:
res.append(i - m)
j = lps[j - 1]
elif j:
j = lps[j - 1]
else:
i += 1
return res
a, b, c = p.split('*')
A, B, C = starts(a), starts(b), starts(c)
la, lb, lc = len(a), len(b), len(c)
ans = len(s) + 1
j = k = 0
for i in A:
while j < len(B) and B[j] < i + la:
j += 1
if j == len(B):
break
while k < len(C) and C[k] < B[j] + lb:
k += 1
if k == len(C):
break
ans = min(ans, C[k] + lc - i)
return -1 if ans > len(s) else ans