Guest User

Untitled

a guest
Feb 23rd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class Solution
  5. {
  6. public static string GetShortestUniqueSubstring(char[] arr, string str)
  7. {
  8. if (arr == null || str == null || arr.Length > str.Length) return "";
  9.  
  10. int uCount = arr.Length;
  11. int n = str.Length;
  12.  
  13. // Count of elements which are present in arr
  14. var count = new Dictionary<char, int>();
  15.  
  16. int i, j;
  17. int min = Int32.MaxValue; // window length
  18. int start = -1; // answer start position
  19.  
  20. for(i = 0; i < uCount; i++){
  21. count[arr[i]] = 0;
  22. }
  23.  
  24. int found = 0; j = 0;
  25. for(i = 0; i <= n- uCount; i++)
  26. {
  27. // at the end of this loop j should be pointing just at the end of thw windows
  28.  
  29.  
  30. while (found != uCount && j < n){
  31. if (count.ContainsKey(str[j])){
  32. if (count[str[j]] == 0){
  33. found++;
  34. }
  35. count[str[j]]++;
  36. }
  37. j++;
  38. }
  39.  
  40. if (found == uCount && (j-i) < min){ // Found a new smaller window
  41. min = j-i;
  42. start = i;
  43. }
  44.  
  45. // If the str[i]
  46. if (count.ContainsKey(str[i])){
  47. if (count[str[i]] == 1){
  48. found--;
  49. }
  50. count[str[i]]--;
  51. }
  52. }
  53.  
  54. if (start == -1) return "";
  55.  
  56. return str.Substring(start, min);
  57.  
  58.  
  59.  
  60.  
  61. /*
  62. xyyzyzyx
  63. i=0 left end of the window
  64. j = right end of the window
  65.  
  66. var count = int [256]
  67. [i,j] = find all the character of arr
  68.  
  69. start with i = 0
  70. find j till all the characters in arr is covered
  71. window - compare it with old window, if it smaller then save it.
  72. i = 1;
  73. decerment the value count[a[0]]--; it doesn't affect the all covering of element in arr
  74. remaining element is less than size of arr
  75. */
  76. }
  77.  
  78. static void Main(string[] args)
  79. {
  80. }
  81. }
Add Comment
Please, Sign In to add comment