首页 > 代码库 > Minimum Window Substring
Minimum Window Substring
题目
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); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。