zoukankan      html  css  js  c++  java
  • 32. 最小子串覆盖

    32. 最小子串覆盖

    中文English

    给定两个字符串 source 和 target. 求 source 中最短的包含 target 中每一个字符的子串.

    样例

    样例 1:

    输入: source = "abc", target = "ac"
    输出: "abc"
    

    样例 2:

    输入: source = "adobecodebanc", target = "abc"
    输出: "banc"
    解释: "banc" 是 source 的包含 target 的每一个字符的最短的子串.
    

    样例 3:

    输入: source = "abc", target = "aa"
    输出: ""
    解释: 没有子串包含两个 'a'.
    

    挑战

    O(n) 时间复杂度

    注意事项

    1. 如果没有答案, 返回 "".
    2. 保证答案是唯一的.
    3. target 可能包含重复的字符, 而你的答案需要包含至少相同数量的该字符.

    解法一:  同向双指针

    class Solution:
        '''
        大致思路:
        1. 给个子函数,判断是否是符合要求的
        2. 双指针解法
        '''
        def minWindow(self, source , target):
            len1, len2 = len(source), len(target)
            if len1 < len2: return ''
    
            # 定义
            left, right = 0, 0
            count = sys.maxsize
            res = ''
            for index in range(len1 - len2 + 1):
                left, right = index, index + len2
                while right <= len1:
                    if self.ifinclude(source[left: right], target):
                        if right - left < count:
                            count = right - left
                            res = source[left: right]
                    right += 1 
    
            return res
    
        
        def ifinclude(self, source, target):
            ''' 判断是否包含 '''    
            source_dict, target_dict = {}, {}
            for val in source:
                source_dict[val] = source_dict.get(val, 0) + 1
            
            for val in target:
                target_dict[val] = target_dict.get(val, 0) + 1
            
            # 判断
            for val in target:
                if val not in source_dict.keys():
                    return False
                else:
                    if target_dict[val] > source_dict[val]:
                        return False
            
            return True

    注意: 时间复杂度超过限制, Lintcode未通过。

  • 相关阅读:
    spring cloud的pigx版本
    SQL Profiler使用
    postmen简单用法
    T-SQL
    常见问题整理
    数据库 新建维护计划
    c# ABP返回格式自定义,去除固定返回格式
    系统综合实践期末大作业 第32组
    系统综合实践第7次实践作业 第32组
    系统综合实践第6次实践作业 第32组
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/14327858.html
Copyright © 2011-2022 走看看