LeetCode76 最小覆盖子串

it2026-08-26  6

给你一个字符串 S、一个字符串 T 。请你设计一种算法,可以在 O(n) 的时间复杂度内,从字符串 S 里面找出:包含 T 所有字符的最小子串。

示例:

输入:S = “ADOBECODEBANC”, T = “ABC” 输出:“BANC”

提示:

如果 S 中不存这样的子串,则返回空字符串 “”。 如果 S 中存在这样的子串,我们保证它是唯一的答案。

题解: 滑动窗口就完事 时间复杂度O(n*字符集大小)

字符本来该是0-127 然鹅,实测里面只有字母…于是开了58。。。

用时 23 ms,内存消耗 38.4 MB,菜鸡如我…

class Solution { public String minWindow(String s, String t) { int[] count = new int[58]; int[] std = new int[58]; for(int i = 0; i < t.length(); i++) { std[(int) t.charAt(i) - 65]++; } int length = 0; int[] index = new int[2]; int left = -1; for(int right = 0; right < s.length(); right++) { count[(int) s.charAt(right) - 65]++; while((left < right) && isCover(count, std)) { if(length == 0 || length > (right - left)) { length = right - left ; index[0] = left; index[1] = right; } left++; count[(int) s.charAt(left) - 65]--; } } if(length == 0) return ""; else return s.substring(index[0] + 1, index[1] + 1); } private boolean isCover(int[] count, int[] std) { for(int i = 0; i < 58; i++) { if(count[i] < std[i]) return false; } return true; } }
最新回复(0)