zoukankan      html  css  js  c++  java
  • 字符统计和滑动窗口

    [LeetCode 76] 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).
    
    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.
    

    测试案例

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

    思路

    1. 先用 record 数组统计出 t 字符串中各字符的个数。
    2. 然后依次遍历 s 中的每个字符。
    3. 用 count 遍历 记录当前串 s[i,j] 中没有涵盖的字符个数。
    4. 遍历的当前字符不是有效字符时,即record[ch] <= 0时,i++。否则,移动 j,剔除冗余字符。直到剔除了第一个有效字符为止,此时更新最小长度和起始下标:min 和 index。
    5. 重复上述过程,直至遍历结束。时间复杂度为:(O(n))

    代码如下

    class Solution {
        public String minWindow(String s, String t) {
            int ns = s.length(), nt = t.length();
            if(ns == 0 || nt == 0){
                return "";
            }
            int index = 0, count = nt, min = ns + 1, pos;
            int[] record = new int[65536];
            //统计t中各字符的个数
            for(int i = 0; i < nt; i++){
                record[t.charAt(i)]++;
            }
            //遍历s中的所有字符,先找到一个包含t的子串
            for(int i = 0, j = 0; i < ns; i++){
                pos = s.charAt(i);
                if(record[pos]-- > 0){
                    count--;
                    //然后缩减左端,直到count = 1为止,记录下长度和起始下标
                    while(count == 0){
                        if(++record[s.charAt(j++)] > 0){
                            count++;
                            if(i - j + 2 < min){
                                min = i - j + 2;
                                index = j - 1;
                            }
                            break;
                        }
                    }
                }
            }
            //当min为s+1时,输出空串,否则输出子串s.substring(index,index + min);
            if(min == ns + 1){
                return "";
            }
            else{
                return s.substring(index, index + min);
            }
        }
    }
    
  • 相关阅读:
    layui动态修改select的选中项
    layui 鼠标悬停单元格显示全部
    使用LayUI操作数据表格
    layer.msg 弹出不同的效果的样式
    layer父页面刷新
    layui 获取radio单选框选中的值
    使用Dapper.Contrib
    微信公众号的文章爬取有三种方式
    centos的 各种安装包下载位置
    git pull一直弹出vim编辑器
  • 原文地址:https://www.cnblogs.com/echie/p/9599943.html
Copyright © 2011-2022 走看看