Advertisement
ogv

Untitled

ogv
Oct 16th, 2019
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.35 KB | None | 0 0
  1. // Runtime: 9 ms, beats 69.12 % of java submissions.
  2. class Solution {
  3.     public String minWindow(String s, String t) {
  4.         int tLength = t.length();
  5.        
  6.         Map<Character, Integer> map = new HashMap<>();
  7.         int[] tCount = new int[tLength];
  8.        
  9.         int charCount = 0;
  10.         for (int i = 0; i < tLength; i++) {
  11.             char c = t.charAt(i);
  12.             Integer ix = map.get(c);
  13.             if (ix == null){
  14.                 ix = charCount++;
  15.                 map.put(c, ix);
  16.             }
  17.             tCount[ix] += 1;
  18.         }
  19.        
  20.         int[] sArray = new int[s.length()];
  21.         for (int i=0; i < s.length(); i++){
  22.             Integer ix = map.get(s.charAt(i));
  23.             sArray[i] = ix != null ? ix: -1;
  24.         }
  25.  
  26.         int minLength = Integer.MAX_VALUE;
  27.         int minPos = 0;
  28.                
  29.         Deque<Integer> idx = new ArrayDeque<Integer>();
  30.         int[] presence = new int[charCount];
  31.         int matchCount = 0;
  32.        
  33.         for (int i = 0; i < sArray.length; i++) {
  34.             int c = sArray[i];        
  35.             if (c == -1) continue;
  36.            
  37.             int pb = presence[c];
  38.            
  39.             idx.addLast(i);                
  40.             presence[c] += 1;              
  41.                      
  42.             for (;;) {
  43.                 int first = sArray[idx.getFirst()];
  44.                 if (presence[first] <= tCount[first]) break;
  45.                
  46.                 idx.removeFirst();
  47.                 presence[first] -= 1;                                
  48.             }
  49.            
  50.             if (presence[c] > pb && presence[c] <= tCount[c]) {                
  51.                 matchCount++;                
  52.             }
  53.                        
  54.             if (matchCount == tLength) {
  55.                 int len = idx.getLast() - idx.getFirst() + 1;
  56.                 if (len < minLength) {
  57.                     minLength = len;
  58.                     minPos = idx.getFirst();
  59.                 }
  60.                
  61.                 int first = sArray[idx.getFirst()];
  62.                 idx.removeFirst();
  63.                 presence[first] -= 1;
  64.                                  
  65.                 matchCount--;
  66.             }
  67.         }
  68.        
  69.         if (minLength == Integer.MAX_VALUE) return "";
  70.        
  71.         return s.substring(minPos, minPos + minLength);    
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement