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

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

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @param t string字符串
     * @return string字符串
     */
    public String minWindow (String s, String t) {
        // write code here
        if (s == null || t == null || s.length() == 0 || t.length() == 0) {
            return "";
        }

        // 统计 t 中各字符出现的次数
        int[] tChars = new int[128];
        for (char c : t.toCharArray()) {
            tChars[c]++;
        }

        int left = 0; // 窗口左边界
        int right = 0; // 窗口右边界
        int minLen = Integer.MAX_VALUE; // 最小子串长度
        int minStart = 0; // 最小子串起始位置
        int count = t.length(); // t 中剩余待匹配的字符数

        while (right < s.length()) {
            char charRight = s.charAt(right);
            if (tChars[charRight] > 0) {
                count--;
            }
            tChars[charRight]--;
            right++;

            while (count == 0) {
                if (right - left < minLen) {
                    minLen = right - left;
                    minStart = left;
                }

                char charLeft = s.charAt(left);
                if (tChars[charLeft] == 0) {
                    count++;
                }
                tChars[charLeft]++;
                left++;
            }
        }

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

Java 编程语言编写的。

该题考察的知识点包括:

  1. 滑动窗口
  2. 哈希表

代码的文字解释:

对字符串 t 进行预处理,统计其中各字符的出现次数,并保存在 tChars 数组中。使用双指针滑动窗口的方法来寻找满足条件的最小子串。通过不断右移 right 指针,处理窗口内的字符。如果字符属于 t 中的字符,我们更新 counttChars 数组。

count 变为 0 时,表示当前窗口内包含了涵盖 t 的所有字符。此时,我们将 left 指针右移,缩小窗口,直到 count 不再为 0。在整个过程中,不断更新 minLenminStart,以找到满足条件的最小子串。

最终,根据 minLenminStart 的值,如果存在满足条件的最小子串,我们通过字符串截取操作返回该子串,否则返回空字符串

全部评论

相关推荐

05-09 13:22
门头沟学院 Java
点赞 评论 收藏
分享
04-25 19:29
已编辑
宁波大学 运营
被普调的六边形战士很高大:你我美牛孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务