Pregunta de entrevista de Meta

Given a string 'alphabet' and a string 'codex' find the shortest substring in codex that contains all characters in alphabet.

Respuesta de la entrevista

Anónimo

15 oct 2015

// Find the minimum window in string S which will contain all the characters of string T // Complexity: O(max(m,n)) - where m is length of s and n is length of t // Space: O(max(m,n)) - where m is length of s and n is length of t public string minimumWindow(string s, string t) { if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t)) return null; if (t.Length > s.Length) return ""; string result = ""; Dictionary shouldFind = new Dictionary(); Dictionary hasFound = new Dictionary(); int count = 0; int j = 0; int minWindow = s.Length + 1; int start = 0; int finish = 0; int sLength = s.Length; int tLength = t.Length; for (int i = 0; i shouldFind[ch]) { if (hasFound.ContainsKey(ch) && hasFound[ch] > shouldFind[ch]) hasFound[ch] = hasFound[ch] - 1; j++; ch = s.ElementAt(j); } //lets find the minimum window if (minWindow > (i - j + 1)) { minWindow = i - j + 1; start = j; finish = i + 1; result = s.Substring(start, (finish - start)); } } } return result; }

1