LeetCode 76 Minimum Window Substring (尺取法 推荐)

70 篇文章 0 订阅
60 篇文章 0 订阅

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).

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return the empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.


题目链接:https://leetcode.com/problems/minimum-window-substring/

题目分析:典型的尺取法问题,先标记下T串有哪些字符及它们的个数,固定左端点,移动右端点直到包含整个T串,然后移动左端点直到不再包含整个T串,此时再继续移动右端点,击败了91%

public class Solution {
    public String minWindow(String s, String t) {
        int lens = s.length();
        int lent = t.length();
        int[] cnt = new int[300];
        boolean[] mark = new boolean[300];
        for (int i = 0; i < lent; i ++) {
            cnt[t.charAt(i)] ++;
            mark[t.charAt(i)] = true;
        }
        int sz = lens + 5, l = 0, num = 0, lpos = 0;
        for (int r = 0; r < lens; r ++) {
            char cur = s.charAt(r);
            if (mark[cur]) {
                cnt[cur] --;
                if (cnt[cur] >= 0) {
                    num ++;
                }
            }
            while (num == lent) {
                if (r - l + 1 < sz) {
                    sz = r - l + 1;
                    lpos = l;
                }
                if (mark[s.charAt(l)]) {
                    cnt[s.charAt(l)] ++;
                    if (cnt[s.charAt(l)] > 0) {
                        num --;
                    }
                }
                l ++;
            }
        }
        if (sz <= lens) {
            return s.substring(lpos, lpos + sz);
        }
        return "";
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值