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 shortestsubstring 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 '*'.
Solutions
Solution 1
Thinking
\(p\) contains exactly two stars and splits into three literals \(a\), \(b\), \(c\). \(|s|,|p|\le 10^5\) forbids a naive search from every start.
The shortest match is determined by occurrence positions: after one \(a\), take the earliest later \(b\), then the earliest later \(c\).
KMP or Z-algorithm lists every occurrence of the three pieces. A two-pointer sweep over \(a\)'s starts advances \(b\) and \(c\). The length is the right end of \(c\) minus the left end of \(a\), or \(-1\) if none exists.
Split the pattern on its two stars into literals \(a\), \(b\), and \(c\). Any of them may be empty. KMP lists every starting index of each literal in \(s\). An empty literal matches at every index \(0,1,\ldots,n\).
For each start \(i\) of \(a\), advance a pointer to the earliest start \(j\) of \(b\) with \(j\ge i+|a|\), then to the earliest start \(k\) of \(c\) with \(k\ge j+|b|\). That match has length \(k+|c|-i\). The minimum over all starts is the answer, or \(-1\) when no match exists.
A later \(b\) can only push \(c\) further right, so the earliest \(b\) and the earliest \(c\) are optimal for a fixed \(i\).
The time complexity is \(O(n+m)\) and the space complexity is \(O(n)\), where \(n\) and \(m\) are the lengths of \(s\) and \(p\).