Sliding Window
IntuitionThe goal is to find the shortest substring of s that contains exactly k instances of the character '1'. The challenge here is to efficiently find and c
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The goal is to find the shortest substring of s that contains exactly k instances of the character '1'. The challenge here is to efficiently find and compare substrings while keeping track of the count of '1's.

# Approach
<!-- Describe your approach to solving the problem. -->
The approach to solving the problem of finding the shortest substring of s that contains exactly k '1's involves using a sliding window technique. We initialize variables to keep track of the string length, ans, and two pointers (i and j) for the window, along with a count for '1's. As the right pointer j expands the window, we increment the count whenever a '1' is encountered. Once the count reaches k, we start shrinking the window from the left pointer i while the count remains equal to k. For each valid window, we extract the substring and compare its length to the current shortest substring. If the new substring is shorter or lexicographically smaller when lengths are equal, we update the result. We then decrement the counter if the character at i is '1' and move the left pointer to continue shrinking the window. This process continues until the right pointer reaches the end of the string, ensuring we find the shortest beautiful substring containing exactly k '1's. The final result is returned after the loop ends.

# Code
```java []
public class Solution {
    public String shortestBeautifulSubstring(String s, int k) {
        int n = s.length();
        String ans = "";
        int i = 0, j = 0;
        int c = 0;
        
        while (j < n) {
            if (s.charAt(j) == '1') c++;
            if (c == k) {
                while (i < n && c == k) {
                    String s1 = s.substring(i, j + 1);
                    if (ans.isEmpty() || s1.length() < ans.length()) ans = s1;
                    else if (s1.length() == ans.length()) ans = (ans.compareTo(s1) < 0) ? ans : s1;
                    if (s.charAt(i) == '1') c--;
                    i++;
                }
            }
            j++;
        }
        return ans;
    }
}
```
['String', 'Sliding Window', 'String Matching', 'Counting', 'Java']