Guest User

MinWindowSubstring

a guest
Sep 22nd, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. public String minWindow(String s, String t) {
  2. if (s == null || t == null || s.length() < t.length()) {
  3. return "";
  4. }
  5.  
  6. Map<Character, Integer> map = new HashMap<>();
  7. for (char c : t.toCharArray()) {
  8. map.put(c, map.getOrDefault(c, 0) + 1);
  9. }
  10.  
  11. // record the min window's start position
  12. int startIndex = 0, minLen = Integer.MAX_VALUE;
  13. int count = map.size();
  14. // left side (left) and right side (right) of sliding window
  15. for (int left = 0, right = 0; right < s.length(); right++) {
  16. char cRight = s.charAt(right);
  17. if (map.containsKey(cRight)) {
  18. map.put(cRight, map.get(cRight) - 1);
  19. if (map.get(cRight) == 0) {
  20. count -= 1;
  21. }
  22. }
  23.  
  24. while (count <= 0) {
  25. char cLeft = s.charAt(left);
  26. if (map.containsKey(cLeft)) {
  27. map.put(cLeft, map.get(cLeft) + 1);
  28. // map.get(cLeft) means cLeft is the start character(position) of curr window
  29. // pay attention to the duplicated characters.
  30. if (map.get(cLeft) >= 1) {
  31. count += 1;
  32. }
  33. }
  34. // Get the min window
  35. if (right - left + 1 < minLen) {
  36. startIndex = left;
  37. minLen = right - left + 1;
  38. }
  39. left++;
  40. }
  41. }
  42. return minLen == Integer.MAX_VALUE ? "" : s.substring(startIndex, startIndex + minLen);
  43. }
Advertisement
Add Comment
Please, Sign In to add comment