zoukankan      html  css  js  c++  java
  • Minimum Window Substring

    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).

    For example,
    S = "ADOBECODEBANC"
    T = "ABC"

    Minimum window is "BANC".

    Note:
    If there is no such window in S that covers all characters in T, return the empty string "".

    If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

    这题比较有意思,但是也比较坑,主要在于题目并没有说清楚如果T包含重复字符时应该如何处理。实际按题目本身的要求,T中字符重复出现在S的window中也需要有同样的出现次数。不考虑顺序只考虑出现次数,则可以先用hashmap存储T中的元素,做一个词频统计处理。之后在S中暴力做法是枚举window起点和终点,之后判断是否满足条件。自然想起用two pointer优化这题。

    class Solution:
        """
        @param source: A string
        @param target: A string
        @return: A string denote the minimum window
                 Return "" if there is no such a string
        """
        def minWindow(self, source, target):
            if not source:
                return ""
            hash = {}
            for i in target:
                if i not in hash:
                    hash[i] = 1
                else:
                    hash[i] += 1
            min_len = sys.maxint
            l = 0
            start = -1
            count = 0
            for r in xrange(len(source)):
                if source[r] in hash:
                    hash[source[r]] -= 1
                    if hash[source[r]] >= 0:
                        count += 1
                    while count == len(target):
                        length = r - l + 1
                        if length < min_len:
                            min_len = length
                            start = l
                        if source[l] in hash:
                            hash[source[l]] += 1
                        if source[l] in hash and hash[source[l]] > 0:
                            count -= 1
                        l += 1
            return source[start: start + min_len] if start > -1 else ""

    具体的难点在于有重复字符时如何判断窗口内是否已累计到需要的量的字符数目。所以以上代码采用了count这个变量来统计是否达到长度。 但是需要注意的是,一个window里面有多于T中某个字符出现频次的字符,count数不需要增加。具体来说因为开始hashmap中频率的值大于0,所以频率值小于0时说明已经出现了足够多的字符。 所以如果这时候字符在hashmap中,也不应该增加。之后在删除l 指针指向的字符时,同样,如果字符删除后,hash表中频率大于0了,说明这个字符影响了统计,所以count要减1.

  • 相关阅读:
    10天掌握webpack 4.0 Html 插件
    10天掌握webpack 4.0 服务篇
    spring boot 国际化信息
    Java 编程下使用 Class.forName() 加载类
    Java 编程下正则表达式判断字符串是否包含中文
    Adb connection Error:远程主机强迫关闭了一个现有的连接 解决方法
    Java 编程下简介 Class 与类加载
    通过htaccess文件配置多个一级域名指向根目录的子文件夹
    apache httpd.conf
    composer安装laravel框架时未生成Vendor解决办法
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5677475.html
Copyright © 2011-2022 走看看