主页 > IT业界  > 

Leetcode3455.ShortestMatchingSubstring

Leetcode3455.ShortestMatchingSubstring
Leetcode 3455. Shortest Matching Substring 1. 解题思路2. 代码实现 题目链接:3455. Shortest Matching Substring 1. 解题思路

这一题我一开始想的是偷懒用一下re库,不过尝试失败了,所以就只能老老实实自己写函数求解了。

然后我的思路就是使用z-algorithm,有关这部分内容的话网上有不少的介绍,我自己也写过一篇博客(经典算法:Z算法(z algorithm))作为备忘,所以这里就不过多展开了,直接说明一下这道题的具体思路就行了。

显然,因为要求最短子串的长度,因此首尾的*符号显然可以直接忽略掉,剩下就是中间的部分,这里就会把pattern字符串p拆分为若干个子字符串,我们需要依次对各个子串进行一下匹配,这里就会用到z算法来找到每一个子串的所有match的位置,然后我们依次考察每一个位置作为第一个字符串的起点时,其所能找到的子串的最短长度即可。

这个的话就只要依次根据上一段子串的结束位置找出下一段子串的最近邻匹配位置即可。我们可以通过二分查找快速实现。

2. 代码实现

给出python代码实现如下:

def z_algorithm(s): n = len(s) z = [0 for _ in range(n)] l, r = -1, -1 for i in range(1, n): if i > r: l, r = i, i while r < n and s[r-l] == s[r]: r += 1 z[i] = r-l r -= 1 else: k = i - l if z[k] < r - i + 1: z[i] = z[k] else: l = i while r < n and s[r-l] == s[r]: r += 1 z[i] = r-l r -= 1 z[0] = n return z class Solution: def shortestMatchingSubstring(self, s: str, p: str) -> int: if p.replace("*", "") in s: return len(p.replace("*", "")) subs = p.strip("*").split("*") if len(subs) == 1: return len(subs[0]) if subs[0] in s else -1 def get_matches_idx(sub): n = len(sub) z = z_algorithm(sub + s)[n:] return [i for i, k in enumerate(z) if k >= n] n = len(subs) ans = math.inf matches = [get_matches_idx(sub) for sub in subs] for st in matches[0]: ed = st+len(subs[0]) for match, sub in zip(matches[1:], subs[1:]): i = bisect.bisect_left(match, ed) if i >= len(match): ed = math.inf break else: ed = match[i] + len(sub) ans = min(ans, ed-st) return ans if ans != math.inf else -1

提交代码评测得到:耗时1015ms,占用内存30.7MB。

标签:

Leetcode3455.ShortestMatchingSubstring由讯客互联IT业界栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Leetcode3455.ShortestMatchingSubstring