标签:
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).
思路:
Hashtable+双指针
我的代码:
public class Solution { public String minWindow(String s, String t) { if(s==null || s.length()==0) return ""; if(t==null || t.length()==0) return ""; int[] mark = new int[256]; int[] valid = new int[256]; for(int i=0; i<t.length(); i++) { mark[t.charAt(i)]++; valid[t.charAt(i)]++; } int minStart = 0; int minSize = Integer.MAX_VALUE; int start = 0; int count = 0; for(int end=0; end<s.length(); end++) { if(mark[s.charAt(end)] > 0) { valid[s.charAt(end)]--; if(valid[s.charAt(end)] >= 0) count++; if(count == t.length()) { while(true) { if(mark[s.charAt(start)] > 0) { if(valid[s.charAt(start)] < 0) valid[s.charAt(start)]++; else break; } start++; } if(minSize > end-start+1) { minSize = end-start+1; minStart = start; } } } } if(minSize == Integer.MAX_VALUE) return ""; return s.substring(minStart, minStart+minSize); } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4493216.html