Given a string s ang string t, find the minmum window in s.
For example:
s = "ADOBENCODEBANC";
t = "ABC";
Minimum window is "BANC";
t = "ABBC";
Minimum window is "BENCODEBA";
我的时间复杂度为O(n2),不是优秀的实现代码,但是也花了我很长时间,我还是想把代码贴出来
思路:找到字符串中第一匹配的字符和最后一个匹配的字符,两者相减之后再加1就是要找的结果(作为哨兵),但这结果并不一定是最优的,还得继续得到下一次结果,然后比较两次结果取最短的,如此循环下去,每次匹配到t中的字符,我就将t中的这个字符删掉,当t的长度小于1时,从字符串中截出第一匹配的字符和最后一个匹配的字符。
public static void main(String[] args) {
String s = "ADOBENCODEBANC";
String t = "ABBC";
String result = s;
for(int i = 0; i < s.length(); ++i){
result = findMinSubstring(s.substring(i), t, result);
}
if(result.length() == s.length() && result != t){
System.out.println("");
}else{
System.out.println(result);
}
}
public static String findMinSubstring(String s, String t, String result) {
StringBuffer sb = new StringBuffer(t);
int firstNum = -1;
int lastNum = -1;
for(int i = 0; i < s.length(); ++i){
if(t.contains(s.charAt(i)+"")){
firstNum = i;
break;
}
}
for(int j = firstNum; j < s.length(); ++j){
if(t.contains(s.charAt(j)+"")){
lastNum = j;
if(sb.toString().contains(s.charAt(j)+""))
sb.deleteCharAt(sb.toString().indexOf(s.charAt(j)));
}
if(sb.length() < 1){
return s.substring(firstNum, lastNum + 1).length() < result.length() ? s.substring(firstNum, lastNum + 1) : result;
}
}
return result;
}