From da5f4c1b323bd4f1ee8346417e30f0a09e331e8a Mon Sep 17 00:00:00 2001 From: Koushambha Das <122219149+KOUSHAMBHA15IT@users.noreply.github.com> Date: Sun, 4 Feb 2024 12:38:20 +0530 Subject: [PATCH] Update Minimum Window Substring.cpp Added the Java code for the question Minimum Window Substring | Leetcode-76 --- Sliding Window/Minimum Window Substring.cpp | 36 +++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Sliding Window/Minimum Window Substring.cpp b/Sliding Window/Minimum Window Substring.cpp index aeffabbb..d3843f72 100644 --- a/Sliding Window/Minimum Window Substring.cpp +++ b/Sliding Window/Minimum Window Substring.cpp @@ -44,3 +44,39 @@ class Solution { return minWindow == INT_MAX ? "" : s.substr(minStart, minWindow); } }; + +// Java code: +class Solution { + public String minWindow(String s, String t) { + int n = s.length(); + Map mp = new HashMap<>(); + for(char ch : t.toCharArray()) { + mp.put(ch, mp.getOrDefault(ch, 0) + 1); + } + int requiredCount = t.length(); + int i = 0, j = 0; + int minStart = 0; + int minWindow = Integer.MAX_VALUE; + while(j < n) { + char ch_j = s.charAt(j); + if(mp.getOrDefault(ch_j, 0) > 0) + requiredCount--; + mp.put(ch_j, mp.getOrDefault(ch_j, 0) - 1); + while(requiredCount == 0) { + if(minWindow > j - i + 1) { + minWindow = j - i + 1; + minStart = i; + } + char ch_i = s.charAt(i); + mp.put(ch_i, mp.get(ch_i) + 1); + if(mp.get(ch_i) > 0) + requiredCount++; + i++; + } + j++; + } + return minWindow == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minWindow); + } +} + +