leetcode76题 Minimum Window Substring
2018-03-11 20:16
531 查看
最小窗口子字符串
题目要求:给定一个字符串S和T,在S中找到一个包含T中所有字符的最短字串,时间复杂度为O(n).注1:如果这个窗口不存在,返回一个空字符串
注2:该题保证在S中总是只有一个唯一的最小窗口
解决思路
采用滑动窗口的方法,首先定义一个HashMap集合,用来记录T中字符出现的次数,同时定义一个计数变量来统计所得到的字符串是否包含T中所有的字符。具体做法为:当定义的滑动窗口的右指针不断向右滑动,找到包含T中所有字符的字串。然后通过控制窗口的滑动,尽可能的减少该字串的长度。
Java语言解决方案
class Solution { public String minWindow(String s, String t) { if(s.length()<t.length()) return ""; char[] ss = s.toCharArray(); char[] tt = t.toCharArray(); int count = t.length(); String res = ""; HashMap<Character,Integer> hm = new HashMap<>(); for(int i=0;i<t.length();i++) if(hm.containsKey(tt[i])) hm.put(tt[i], hm.get(tt[i])+1); else hm.put(tt[i], 1); int l=0,r=0; while(r<s.length()){ if(hm.containsKey(ss[r])){ if(hm.get(ss[r])>0) count--; hm.put(ss[r], hm.get(ss[r])-1); } while(l<=r&&count==0){ if(res.isEmpty()||res.length()>(r-l+1)) res = s.substring(l,r+1); if(hm.containsKey(ss[l])){ hm.put(ss[l], hm.get(ss[l])+1); if(hm.get(ss[l])>0) count++; } l++; } r++; } return res; } }
题目链接: https://leetcode.com/problems/minimum-window-substring/description/
相关文章推荐
- LeetCode 76: Minimum Window Substring
- leetcode 76: Minimum Window Substring
- 【leetcode 76】 Minimum Window Substring
- 【LeetCode 76】 Minimum Window Substring
- Leetcode 76 Minimum Window Substring(最小窗口的子串)
- LeetCode 76 minimum window substring
- leetcode[76]Minimum Window Substring
- LeetCode 76 Minimum Window Substring(Python详解及实现)
- LeetCode76 Minimum Window Substring
- LeetCode 76 Minimum Window Substring
- LeetCode 76 Minimum Window Substring (尺取法 推荐)
- LeetCode_OJ【76】Minimum Window Substring
- LeetCode76——Minimum Window Substring
- LeetCode 76 Minimum Window Substring
- leetcode-76 Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- LeetCode(76) Minimum Window Substring
- leetcode hard模式专杀之76 Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- LeetCode(76) Minimum Window Substring