Untitled
public class LongestSubstringKUnique { public static void findLongestSubstring(String str, int k) { if (str == null || str.length() == 0) { System.out.println("Invalid input"); return; } // Check if there are enough unique characters int uniqueCount = (int) str.chars().distinct().count(); if (uniqueCount < k) { System.out.println("Not enough unique characters"); return; } // Initialize pointers, data structures, and variables int i = 0; // Start pointer of the sliding window int j = 0; // End pointer of the sliding window int[] charCount = new int[26]; // Frequency array for 'a' to 'z' int maxLength = 0; // To store the maximum length of the substring int maxStart = 0; // To store the start index of the longest substring // Traverse the string using the end pointer (j) while (j < str.length()) { char c = str.charAt(j); // Add the current character to the frequency array charCount[c - 'a']++; // Shrink the window until there are exactly k unique characters while (countUniqueCharacters(charCount) > k) { char leftChar = str.charAt(i); charCount[leftChar - 'a']--; i++; // Move the start pointer forward } // Update the maximum length if the current window is valid if (countUniqueCharacters(charCount) == k && (j - i + 1) > maxLength) { maxLength = j - i + 1; maxStart = i; } // Expand the window by moving the end pointer j++; } // Output the result System.out.println("Longest substring length: " + maxLength); if (maxLength > 0) { System.out.println("Substring: " + str.substring(maxStart, maxStart + maxLength)); } } // Helper method to count unique characters in the array private static int countUniqueCharacters(int[] charCount) { int count = 0; for (int freq : charCount) { if (freq > 0) { count++; } } return count; } public static void main(String[] args) { findLongestSubstring("aabbcc", 1); // Output: 2 findLongestSubstring("aabbcc", 2); // Output: 4 findLongestSubstring("aabbcc", 3); // Output: 6 findLongestSubstring("aaabbb", 3); // Output
Leave a Comment