Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.14 KB | None | 0 0
  1. /*
  2. https://leetcode.com/problems/minimum-window-substring
  3. Runtime: 9 ms, faster than 69.12% of Java online submissions for Minimum Window Substring.
  4. Memory Usage: 39 MB, less than 68.09% of Java online submissions for Minimum Window Substring.
  5. */
  6. class Solution {
  7.     public String minWindow(String s, String t) {
  8.         if (t.length() > s.length()) return "";
  9.         HashSet<Character> allowed = new HashSet<>();
  10.         int countdown = 0;
  11.         int[] required = new int[256], found = new int[256], min = new int[] {Integer.MAX_VALUE, 0, 0};
  12.         for (char c : t.toCharArray()) {
  13.             if (allowed.add(c)) {
  14.                 ++countdown;
  15.             }
  16.             ++required[c];
  17.         }
  18.         LinkedList<Tuple> matched = new LinkedList<>();
  19.         char[] chars = s.toCharArray();
  20.         for (int index = 0; index < chars.length; index++) {
  21.             char symbol = chars[index];
  22.             if (allowed.contains(symbol)) {
  23.                 matched.addLast(new Tuple(index, symbol));
  24.                 if(++found[symbol] == required[symbol]) {
  25.                     if(--countdown == 0) {
  26.                         while(countdown == 0) {
  27.                             Tuple left = matched.poll();
  28.                             if (allowed.contains(left.symbol)) {
  29.                                 if (min[0] > index - left.index) {
  30.                                     min[0] = index - left.index;
  31.                                     min[1] = left.index;
  32.                                     min[2] = index;
  33.                                 }
  34.                                 if(--found[left.symbol] < required[left.symbol]) {
  35.                                     ++countdown;
  36.                                 }
  37.                             }
  38.                         }
  39.                     }
  40.                 }
  41.             }
  42.         }
  43.         return min[0] < Integer.MAX_VALUE ? s.substring(min[1], min[2] + 1) : "";
  44.     }
  45.  
  46.     private static class Tuple {
  47.         public int index;
  48.         public char symbol;
  49.         public Tuple(int index, char symbol) {
  50.             this.index = index;
  51.             this.symbol = symbol;
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement