Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 3, 2017 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/557ee262aaaabd0a3151b83c90a7a65a to your computer and use it in GitHub Desktop.
Save jianminchen/557ee262aaaabd0a3151b83c90a7a65a to your computer and use it in GitHub Desktop.
minimum substring - version 1, pass 2 test cases, fail 5 test cases.
using System;
using System.Linq;
class Solution
{
public static string GetShortestUniqueSubstring(char[] arr, string str)
{
if(arr == null || arr.Length == 0 || str.Length == 0) // false
{
return string.Empty;
}
var length = arr.Length;// 3
var searchLength = str.Length; // 8
var minimumSubstring = "";
var minimumLength = searchLength + 1;// 9
var uniqueCharsMet = 0;
int left = 0;
var dictionary = arr.ToDictionary(c=>c, c=>1); // dictionary['x'] = 1, same as 'y', 'z'
for (int index = 0; index < searchLength; index++) // 0, 1, 2, 3, 4
{
var visit = arr[index]; // 'x', 'y', 'y', 'z', 'y'
var isInSet = dictionary.ContainsKey(visit); // true, true, true, true, true
if(!isInSet)
{
continue;
}
var isNeeded = dictionary[visit] > 0; // true, true, false, true, false
if(isNeeded)
{
uniqueCharsMet++; // 1, 2, 3
}
dictionary[visit]--; // d['x'] = 0; d['y'] = 0; d['y'] = -1, d['z'] = 0, d['y'] = -2
while(uniqueCharsMet == length) // 1 != 3, false; 2 != 3, false; 2!= 3, false; true, false
{
// check to see if the left point can move forward
if(!dictionary.ContainsKey(arr[left]) || dictionary[arr[left]] <= 0) // "xyyz"
{
var current = arr[left]; // 'x'
var count = dictionary[current]; // 0
if (count <= 0) // true
{
if (count == 0)
{
uniqueCharsMet--; // 2
}
dictionary[current]++; // dictionary['x'] = 1
}
// maintain substring length
var startPosition = left; // 0
var currentLength = index - startPosition + 1; // 4
var currentSubstring = str.Substring(startPosition, currentLength); //"xyyz"
if(currentLength < minimumLength) // 4 < 9
{
minimumLength = currentLength; // 4
minimumSubstring = currentSubstring; // "xyyz"
}
left++; // 1
}
}
}
return minimumLength == (searchLength + 1) ? string.Empty : minimumSubstring;
}
static void Main(string[] args)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment