美文网首页算法学习
算法题--找到最短匹配子序列

算法题--找到最短匹配子序列

作者: 岁月如歌2020 | 来源:发表于2020-04-21 13:28 被阅读0次
image.png

0. 链接

题目链接

1. 题目

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

If there is no such window in S that covers all characters in T, return the empty string "".
If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

2. 思路1:快慢指针滑动窗口

  1. 初始值
match = left = right = start = end = 0

match: 匹配的数量
left: 慢指针
right: 快指针
start: 最短子序列左端, 左闭区间
end: 最短子序列右端, 右开区间
  1. 先固定left, 让right向右滑动, 直至match匹配成功
  2. 再让left向右滑动, 直至match不能匹配, 过程中不断缩短[start, end)区间大小, 然后继续2, 直至right抵达最右边。
  3. 将得到的[start, end)区间字符串返回, 如果未匹配到(即end == 0), 则返回空字符串

3. 代码

# coding:utf8
from collections import defaultdict


class Solution:
    def minWindow(self, s: str, t: str) -> str:
        needs = defaultdict(int)
        for i in range(len(t)):
            needs[t[i]] += 1

        match = start = end = left = right = 0
        window = defaultdict(int)

        while right < len(s):
            window[s[right]] += 1
            if (s[right] in needs) and (window[s[right]] == needs[s[right]]):
                match += 1
            right += 1

            while match == len(needs):
                if s[left] in needs:
                    window[s[left]] -= 1
                    if window[s[left]] < needs[s[left]]:
                        match -= 1
                if end == 0 or right - left < end - start:
                    start = left
                    end = right
                left += 1

        return s[start: end] if end > 0 else ''


solution = Solution()
print(solution.minWindow('ADOBECODEBANC', 'ABC'))
print(solution.minWindow('AB', 'ABC'))
print(solution.minWindow('ABDCABCE', 'ABC'))
print(solution.minWindow('A', 'A'))

输出结果

BANC

CAB
A

4. 结果

image.png

相关文章

  • 算法题--找到最短匹配子序列

    0. 链接 题目链接 1. 题目 Given a string S and a string T, find th...

  • 刷题

    深度优先搜索,小蜜蜂采蜜最短路径 LeetCode经典题 1. 贪心算法 455 分发糖果376 摇摆序列402 ...

  • bigger is greater

    heckerrank 算法题。 原题地址 此题大意为找到,字典序的下一个最小序列。 input output 通过...

  • kmp_algorithm

    tips:kmp算法分两个步骤:1)计算子串的next数组2)匹配子串conclusion:其实求next数组和匹...

  • 每天一道算法题||DAY3

    今天的算法题:用分治法解决DAY1的排序题,设计更高效的算法。 输入:n个数的一个序列 输出:输入序列的一个排列<...

  • 地图与寻路(一) A星算法及优化

    A星算法其实并不是最短路径算法,它找到的路径并不是最短的,它的目标首先是能以最快的速度找到通往目的地的路,它的时间...

  • 最短路径 之 Dijkstra 算法

    • 最短路径 之 Floyd 算法• 最短路径 之 Bellman 算法 Dijkstra算法是用于求解单源最短路...

  • 最长公共子串与最长公共子序列

    最长公共子串 参考文献 经典算法题每日演练——第四题 最长公共子序列

  • bash字符串操作的%/%%/#/##操作符

    删除最短的前缀匹配子串:# 格式:${str#${prefix}} 从 的最左边开始匹配 ,一旦满足,则删除匹配上...

  • 最短路径 之 Bellman 算法

    • 最短路径 之 Floyd 算法• 最短路径 之 Dijkstra 算法 Bellman算法差不多是Floyd算...

网友评论

    本文标题:算法题--找到最短匹配子序列

    本文链接:https://www.haomeiwen.com/subject/hlsuihtx.html