给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “”
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。
示例 1:
输入:s = “ADOBECODEBANC”, t = “ABC” 输出:“BANC”
示例 2:
输入:s = “a”, t = “a” 输出:“a”
首先感觉此题没有意义,
通过答案设计十分巧妙。学习一下。
package com.javacase;
public class LearnForEveryDay {
public static void main(String[] args) {
String s="ADOBECODEBANC";
String t="ABC";
LearnForEveryDay main = new LearnForEveryDay();
System.out.println(LearnForEveryDay.minWindow(s, t));
String ss="a";
String tt="a";
System.out.println(LearnForEveryDay.minWindow(ss, tt));
}
public static String minWindow(String s, String t) {
//创建int 数组ta 长度128 默认数值均为0
int[] ta = new int[128];
//创建int 数组sa 长度128 默认数值均为0
int[] sa = new int[128];
int min = Integer.MAX_VALUE;
String minWin = "";
// 循环字符串t的每个字符,并设置ta数组对应的值为1
for (int i = 0; i < t.length(); i++) {
ta[t.charAt(i)]++; // t.chartAt(0)=A; char类型的A 转换为int时值为65; 即ta[65]默认为0; ta[65]++ 为1
}
int count = 0;
int end = 0;
int start = 0;
while (end < s.length()) {
if (ta[s.charAt(end)] != 0) {
if (sa[s.charAt(end)] < ta[s.charAt(end)]) {
count++;
}
sa[s.charAt(end)]++;
}
if (count == t.length()) {
while (ta[s.charAt(start)] == 0 || sa[s.charAt(start)] > ta[s.charAt(start)]) {
if (sa[s.charAt(start)] > ta[s.charAt(start)]) {
sa[s.charAt(start)]--;
}
start++;
}
if (end - start + 1 < min) {
minWin = s.substring(start, end + 1);
min = end - start + 1;
}
}
end++;
}
return minWin;
}
}