每日一题day1(Leetcode 76最小覆盖子串)

1.题目解析

1.该题"讲人话"就是在一个字符串s中找到一个最短的能够涵盖子串所有字符的子串

2.解法

  1. 解法1(暴力枚举+hash表)
cpp 复制代码
class Solution {
public:
    string minWindow(string s, string t) {
        int m = s.size();
        int n = t.size();
        if (m < n)
            return "";                 // 解决实例3的特殊情况
        unordered_map<char, int> need; // 统计t中的字符需要的次数
        for (auto c : t) {
            need[c]++;
        }
        int required = need.size(); // 记录字符种类
        int len = INT_MAX;
        int start = 0; // 记录子串开始位置为后续返回字符串奠定基础
        for (int i = 0; i < m; i++) {
            int matched = 0;
            unordered_map<char, int> window;
            for (int j = i; j < m; j++) {
                char c = s[j];
                if (need.count(c)) { // 筛除不必要的元素
                    window[c]++;     // 记录子串中字符出现次数
                    if (window[c] == need[c])
                        matched++; // 达到目标
                }
                if (matched == required) {
                    int currentlen = j - i + 1;

                    if (currentlen < len) {
                        len = currentlen;
                        start = i; // 更新位置
                    }
                    break;
                }
            }
        }
        return len == INT_MAX ? "" : s.substr(start, len);
    }
};

虽然这种解题方法容易想但是作为一道困难题是绝对不可能让你暴力(O(n^2))过的,这个时候我们就需要在暴力的基础上进行优化
我们此处可以选择使用滑动窗口的方式对该问题进行优化

  1. 解法2(滑动窗口+手动hash)
cpp 复制代码
class Solution {
public:
    string minWindow(string s, string t) {

        int hash1[128] = {0}; // 统计t内字符出现的次数
        int kinds = 0;//统计有效字符个数
        for (auto ch : t) {
            if (hash1[ch]++ == 0)
                kinds++;
        }

        int hash2[128] = {0};
        int minlen = INT_MAX, begin = -1;
        for (int left = 0, right = 0, count = 0; right < s.size(); right++) {
            char in = s[right];
            if (++hash2[in] == hash1[in])//进窗口加维护count
                count++;
            while (count == kinds) {//判断
                if (right - left + 1 < minlen) {//更新结果
                    minlen = right - left + 1;
                    begin = left;
                }
                char out = s[left++];//出·窗口维护count
                if (hash2[out]-- == hash1[out])
                    count--;
            }
        }
        if (begin == -1)
            return "";
        else
            return s.substr(begin, minlen);
    }
};
相关推荐
硕风和炜20 分钟前
【LeetCode: 2492. 两个城市间路径的最小分数 + DFS】
java·算法·leetcode·深度优先·dfs·bfs·并查集
我是一颗柠檬1 小时前
【Java项目技术亮点】加权轮询负载均衡算法
java·算法·负载均衡
灯厂码农1 小时前
C语言动态内存分配完全指南(malloc、calloc、realloc、free)
java·c语言·算法
凯瑟琳.奥古斯特3 小时前
K次取反最大化数组和解法(力扣1005)
开发语言·c++·算法·leetcode·职场和发展
Jerry3 小时前
LeetCode 203. 移除链表元素
算法
地平线开发者3 小时前
征程 6 | 工具链 QAT ObserverBase 源码解析
算法
地平线开发者4 小时前
【地平线 征程 6 工具链进阶教程】QAT 训练常见问题和排查
算法
地平线开发者4 小时前
征程 6 | 直方图量化配置与校准实例
算法
地平线开发者4 小时前
征程 6E/M Matrix 开发评板使用系列(一):开箱与点亮
算法·自动驾驶