Untitled
unknown
plain_text
a month ago
1.7 kB
3
Indexable
import java.util.*; public class MinimumWindowSubstring { public static String minWindow(String s, String t) { // Initialize variables int n = s.length(); int m = t.length(); int[] arr = new int[256]; int i = 0, j = 0, minLen = Integer.MAX_VALUE; int leftBoundary = -1, int rightBoundary = -1 , count = 0; // Populate the hash map with characters of string t for (int k = 0; k < m; k++) { arr[t.charAt(k)]++; } // Start the sliding window while (j < n) { // Expand the window by including characters from s if (arr[s.charAt(j)] > 0) { count++; } arr[s.charAt(j)]--; // When a valid window is found while (count == m) { // Update the minimum length and boundaries if (j - i + 1 < minLen) { minLen = j - i + 1; leftBoundary = i; rightBoundary = j; } // Shrink the window from the left arr[s.charAt(i)]++; if (arr[s.charAt(i)] > 0) { count--; } i++; } j++; } // Return the minimum window substring or an empty string if no valid window is found return leftBoundary == -1 ? "" : s.substring(leftBoundary, rightBoundary + 1); } public static void main(String[] args) { String s = "ADOBECODEBANC"; String t = "ABC"; System.out.println("Minimum Window Substring: " + minWindow(s, t)); } }
Editor is loading...
Leave a Comment