题解 | #寻找完成任务所需最短时间#

寻找完成任务所需最短时间

https://www.nowcoder.com/practice/107342346ad44329a35c7e5b890e7d40

知识点:滑动窗口

题目要求找到最短的符合要求的子字符串,我们可以使用滑动窗口的思想,右指针向右滑动,若窗口内的子字符串包含了目标字符串,则将其记录下来,同时,尝试将左指针右移,以缩小窗口大小,得到长度尽可能短的子字符串,当不再符合条件时,右指针右移,继续寻找后续符合条件的子字符串。

Java题解如下

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @param t string字符串 
     * @return string字符串
     */
    public String minWindow (String s, String t) {
        // write code here
        Map<Character, Integer> target = new HashMap<>();
        for(int i = 0; i < t.length(); i++) {
            target.put(t.charAt(i), target.getOrDefault(t.charAt(i), 0) + 1);
        }
        int n = s.length();
        int left = 0, right = 0;
        int len = n;
        String res = "";
        Map<Character, Integer> cnt = new HashMap<>();
        while(right < n) {
            cnt.put(s.charAt(right), cnt.getOrDefault(s.charAt(right), 0) + 1);
            while(check(cnt, target)) {
                if(right - left + 1 < len) {
                    len = right - left + 1;
                    res = s.substring(left, right + 1);
                }
                cnt.put(s.charAt(left), cnt.get(s.charAt(left)) - 1);      
                left++;          
            }
            right++;
        }
        return res;
    }

    private boolean check(Map<Character, Integer> cnt, Map<Character, Integer> target) {
        for(Map.Entry<Character, Integer> entry: target.entrySet()) {
            if(!cnt.containsKey(entry.getKey()) || cnt.get(entry.getKey()) < entry.getValue()) {
                return false;
            }
        }
        return true;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务