Untitled

mail@pastecode.io avatar
unknown
java
a year ago
1.7 kB
7
Indexable
Never
import java.util.Arrays;

public class MinSubstrLenForPermutation {
    public static boolean containsPermutation(String s1, String s2) {
        int[] countS1 = new int[10];
        int[] countS2 = new int[10];

        for (char c : s2.toCharArray()) {
            countS2[c - '0']++;
        }

        for (char c : s1.toCharArray()) {
            countS1[c - '0']++;
        }

        for (int i = 0; i < 10; i++) {
            if (countS1[i] < countS2[i]) {
                return false;
            }
        }

        return true;
    }

    public static int[] minSubstrLenForPermutation(String s, String[] arr) {
        int[] result = new int[arr.length];
        Arrays.fill(result, -1);

        for (int k = 0; k < arr.length; k++) {
            String pattern = arr[k];
            int minLen = Integer.MAX_VALUE;
            boolean found = false;

            for (int i = 0; i < s.length(); i++) {
                for (int j = i + pattern.length(); j <= s.length(); j++) {
                    String substr = s.substring(i, j);

                    if (containsPermutation(substr, pattern)) {
                        minLen = Math.min(minLen, j - i);
                        found = true;
                    }
                }
            }

            if (found) {
                result[k] = minLen;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        String s = "064819848398";
        String[] arr = { "088", "364", "07" };

        int[] result = minSubstrLenForPermutation(s, arr);

        System.out.println(Arrays.toString(result)); // Output: [7, 10, -1]
    }
}