Minimum Window Substring
来源:互联网 发布:正当防卫3优化怎么样 编辑:程序博客网 时间:2024/05/22 00:13
题目
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"
.Note:
If there is no such window in S that covers all characters in T, return the emtpy string""
.If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
方法
首先找到一个包含所有T的窗口,逐步右移。使用begin和end来标记窗口的起始。public String minWindow(String S, String T) { if (S == null || T == null) { return null; } if (T.equals("") || S.equals("")) { return ""; } Map<Character, Integer> needFind = new HashMap<Character, Integer>(); Map<Character, Integer> hasFind = new HashMap<Character, Integer>(); int lenS = S.length(); int lenT = T.length(); for (int i = 0; i < lenT; i++) { char ch = T.charAt(i); if (!needFind.containsKey(ch)) { needFind.put(ch, 1); hasFind.put(ch, 0); } else { needFind.put(ch, needFind.get(ch) + 1); } } int newBegin = -1; int newEnd = S.length(); int count = 0; for (int begin = 0, end = 0; end < lenS; end++) { char ch = S.charAt(end); if (needFind.containsKey(ch)) { hasFind.put(ch, hasFind.get(ch) + 1); if (hasFind.get(ch) <= needFind.get(ch)) { count++; } if (count == lenT) { char temp = S.charAt(begin); while(!needFind.containsKey(temp) || hasFind.get(temp) > needFind.get(temp)) { if (needFind.containsKey(temp) && hasFind.get(temp) > needFind.get(temp)) { hasFind.put(temp, hasFind.get(temp) - 1); } begin = begin + 1; temp = S.charAt(begin); } if (end - begin < newEnd - newBegin) { newEnd = end; newBegin = begin; } } } } if (newBegin == -1) { return ""; } else { return S.substring(newBegin, newEnd + 1); } }
0 0
- LeetCode: Minimum Window Substring
- LeetCode Minimum Window Substring
- LeetCode : Minimum Window Substring
- [LeetCode] Minimum Window Substring
- [Leetcode] Minimum Window Substring
- Minimum Window Substring
- LeetCode: Minimum Window Substring
- Minimum Window Substring
- [LeetCode]Minimum Window Substring
- Minimum Window Substring
- Minimum Window Substring
- [leetcode]Minimum Window Substring
- Minimum Window Substring
- Leetcode:Minimum Window Substring
- LeetCode-Minimum Window Substring
- [leetcode] Minimum Window Substring
- [leetcode] Minimum Window Substring
- leetcode Minimum Window Substring
- HDU 1063 Exponentiation 浮点数的幂次方
- 无聊 学下java
- HDU 1018 Big Number N!的位数
- 【JavaScript 封装库】BETA 3.0 测试版发布!
- 第十八周工作总结
- Minimum Window Substring
- 网页向女友/老婆告白和纪念日专用特效
- [Python网络编程]浅析守护进程后台任务的设计与实现
- 一些HTML的记录
- NYOJ 62 笨小熊
- 使用WinDbg抓取程序报错的Dump文件
- 查询数据库MSSQL2005表主键,一行显示
- 开始写写文章吧
- iBatis映射文件详解(一)