Guest User

Untitled

a guest
Feb 17th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class Solution
  5. {
  6. public static string GetShortestUniqueSubstring(char[] keys, string source)
  7. {
  8. if(keys == null || source == null || source.Length == 0 || keys.Length ==0)
  9. {
  10. return "";
  11. }
  12.  
  13. var dictionary = addToDictionary(keys);
  14. var hashSet = new HashSet<char>(keys);
  15.  
  16. int left = 0;
  17. int minLength = int.MaxValue;
  18. int countOfKeys = 0;
  19.  
  20. int length = source.Length;
  21. int startIndex = 0;
  22.  
  23. for(int index = 0; index < length; index++) // axyyz
  24. {
  25. var current = source[index]; // 'a'
  26.  
  27. var isInDict = dictionary.ContainsKey(current);
  28. if(!isInDict)
  29. {
  30. continue;
  31. }
  32.  
  33. if(dictionary[current] == 1)
  34. {
  35. countOfKeys++; // 1, 2, 3
  36. }
  37.  
  38. dictionary[current]--; // x :0, y: -1, z:0
  39.  
  40. // find substring containing all keys
  41. // "xyyz"
  42. // "xxyyz" -> "xyyz"
  43. // "xaxyz" -> "xyz"
  44. while(countOfKeys == keys.Length) // true axyyz
  45. {
  46. var currentLength = index - left + 1; // 4 - 0 + 1 = 5, 4
  47. if(currentLength < minLength)
  48. {
  49. minLength = currentLength; // 5, 4, left = 1
  50. startIndex = left;
  51. }
  52.  
  53. var leftChar = source[left]; // 'a', 'x'
  54. if(!hashSet.Contains(leftChar)) // true
  55. {
  56. left++; // 1
  57. continue;
  58. }
  59.  
  60. dictionary[leftChar]++; // 1
  61. left++; // 2
  62. if(dictionary[leftChar] == 1)
  63. {
  64. countOfKeys--; // 2
  65. }
  66. }
  67. }
  68.  
  69. return minLength == int.MaxValue? "" : source.Substring(startIndex, minLength);
  70. }
  71.  
  72. private static Dictionary<char, int> addToDictionary(char[] keys)
  73. {
  74. var dict = new Dictionary<char, int> ();
  75.  
  76. foreach(var item in keys)
  77. {
  78. dict.Add(item, 1);
  79. }
  80.  
  81. return dict;
  82. }
  83.  
  84. static void Main(string[] args)
  85. {
  86. }
  87. }
Add Comment
Please, Sign In to add comment