问题描述:给定字符串S,子串T,求S中包含T的最小窗口

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

算法分析:对于滑动窗口的题目,一般都是设置左右指针。这道题,首先用map1统计T中每个字符数,然后遍历S字符串,用map2统计T中字符在S中的个数,用count记录相同字符数,如果count==t.length说明当前窗口包含T,然后通过map2对比map1,来滑动窗口。

public class MinWindowSubstring
{
public String minWindow(String s, String t) {
if(t.length()>s.length())
return "";
String result = ""; //统计t中每个字符的个数
HashMap<Character, Integer> target = new HashMap<Character, Integer>();
for(int i=0; i<t.length(); i++)
{
char c = t.charAt(i);
if(target.containsKey(c))
{
target.put(c,target.get(c)+1);
}
else
{
target.put(c,1);
}
} //map统计t中字符在s中的个数
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int left = 0;//窗口左指针
int minLen = s.length()+1;//最小窗口 int count = 0; // 统计s中包含t中元素数 for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i); if(target.containsKey(c))
{
if(map.containsKey(c))
{
if(map.get(c)<target.get(c))
{
count++;
}
map.put(c,map.get(c)+1);
}
else
{
map.put(c,1);
count++;
}
}//target.containsKey(c) if(count == t.length())//当前窗口包含所有t中元素
{
char sc = s.charAt(left);
//从左边开始滑动窗口
while (!map.containsKey(sc) || map.get(sc) > target.get(sc))
{
if (map.containsKey(sc) && map.get(sc) > target.get(sc))
{
map.put(sc, map.get(sc) - 1);
} left++; sc = s.charAt(left);
}
//计算最小窗口
if (i - left + 1 < minLen)
{
result = s.substring(left, i + 1);
minLen = i - left + 1;
}
}//count == t.length }//for return result;
}
}

最新文章

  1. JS虚拟键盘
  2. IBatis学习
  3. 【转】mysql安装图解
  4. 《JavaScript权威指南》读书笔记(四)
  5. Windows 10 LNK File分析
  6. Android中不混淆类中函数
  7. Connecting Universities
  8. 加载window事件
  9. 用JS添加文本框案例代码
  10. HDU 1176 免费馅饼:dp
  11. MySQL高可用架构之MHA 原理与实践
  12. html5 contenteditable 实现table可编辑(网页版EXCEL)
  13. if-else语句
  14. 如何生成SSH key及查看SSH key
  15. 非常不错的地区三级联动,js简单易懂。封装起来了
  16. 关于CALayer 中的contents(图片) 拉伸
  17. python下的Box2d物理引擎的配置
  18. SpringData_CrudRepository接口
  19. #leetcode刷题之路21-合并两个有序链表
  20. ubuntu 安装linux 下vmVMware tools 步骤及问题解决

热门文章

  1. iOS UITableView划动删除的实现
  2. shop++源码反编译----随笔
  3. Linux磁盘分区的理解
  4. javascript的解析过程
  5. 商业模式画布模板——From 《商业模式新生代》
  6. Android学习十---Android Camera
  7. 基于mondrian聚合表的R计算olap开发
  8. Java NIO2 File API介绍
  9. IE调试页面总结
  10. 大家一起来学 NHibernate+NUnit (VS2012+SQL Server2008)