Untitled

 avatar
unknown
plain_text
25 days ago
2.5 kB
1
Indexable
import java.util.HashMap;

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
        HashMap<Character, Integer> charCount = new HashMap<>();
        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 current character to the map and increment its count
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);

            // If the window has more than k unique characters, shrink it
            while (charCount.size() > k) {
                char leftChar = str.charAt(i);
                charCount.put(leftChar, charCount.get(leftChar) - 1);
                if (charCount.get(leftChar) == 0) {
                    charCount.remove(leftChar);
                }
                i++; // Move the start pointer forward
            }

            // Update the maximum length if the current window is valid
            if (charCount.size() == 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));
        }
    }

    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: Not enough unique characters
    }
}
Leave a Comment