栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

leetcode/含有所有字符的最短字符串

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode/含有所有字符的最短字符串

代码
package com.xcrj;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class Solution17 {
    // Map<字符,出现次数>
    private Map tmap = new HashMap<>();
    //
    private Map smap = new HashMap<>();

    
    public String minWindow1(String s, String t) {
        // 特殊情况
        if (s.length() < t.length()) {
            return "";
        }

        // 统计t中字符
        for (char c : t.toCharArray()) {
            tmap.put(c, tmap.getOrDefault(c, 0) + 1);
        }

        int minLen = Integer.MAX_VALUE;
        int start = 0;
        int l = 0;
        int r = -1;
        // !!!记住这个滑动窗口的双wihle模板代码
        while (r < s.length()) {
            // 右移r:r不停的右移,直到l~r的字符都包含在t中
            r++;
            if (r < s.length() && tmap.containsKey(s.charAt(r))) {
                // 统计t包含 s字符串的l~r字符
                smap.put(s.charAt(r), smap.getOrDefault(s.charAt(r), 0) + 1);
            }
            // 右移l:检查l~r的s子串中的每个字符的数量>=t中每个字符的数量,尝试右移l
            while (l <= r && check1()) {
                // 右移l过程中判断最小长度
                if (r - l + 1 < minLen) {
                    minLen = r - l + 1;
                    start = l;
                }
                // 统计,剔除l指向的s中的字符
                if (smap.containsKey(s.charAt(l))) {
                    smap.put(s.charAt(l), smap.get(s.charAt(l)) - 1);
                }
                l++;
            }
        }

        return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen);
    }

    
    public boolean check1() {
        for (Map.Entry tentry : tmap.entrySet()) {
            // l~r在smap中统计的字符数量 一定要>= tmap统计的字符数量,如果小于则不满足 s(l~r)要包含t中所有字符的条件,如果>则存在右移的机会
            if (smap.getOrDefault(tentry.getKey(), 0) < tentry.getValue()) {
                return false;
            }
        }
        // l~r的s子串中的每个字符的数量>=t中每个字符的数量
        return true;
    }

    public static void main(String[] args) {
        Solution17 solution17 = new Solution17();
        System.out.println(solution17.minWindow1("a", "b"));
    }
}

参考

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/M1oyTv/solution/han-you-suo-you-zi-fu-de-zui-duan-zi-fu-a8q50/
来源:力扣(LeetCode)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1035538.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号