06 Longest Substring with Same Letters after Replacement (hard) √

0

Problem Statement

Given a string with lowercase letters only, if you are allowed to replace no more than **k** letters with any letter, find the length of the longest substring having the same letters after replacement.

Example 1:

Input: String="aabccbb", k=2 Output: 5 Explanation: Replace the two 'c' with 'b' to have the longest repeating substring "bbbbb".

Example 2:

Input: String="abbcb", k=1 Output: 4 Explanation: Replace the 'c' with 'b' to have the longest repeating substring "bbbb".

Example 3:

Input: String="abccde", k=1 Output: 3 Explanation: Replace the 'b' or 'd' with 'c' to have the longest repeating substring "ccc".

     public static int findLength1(String str, int k) {
        HashMap<Character, Integer> map = new HashMap<>();
        char[] chars = str.toCharArray();
        int start = 0;
        int result = Integer.MIN_VALUE;
        int currentMax = 0;
        for(int i = 0; i < chars.length; i++){
            char c = chars[i];
            map.put(chars[i],map.getOrDefault(c,0) + 1);
            if(map.getOrDefault(c,0) > currentMax){
                currentMax = map.getOrDefault(c,0);
            }

            if (currentMax + k < i - start + 1) {
                map.put(chars[start],map.getOrDefault(chars[start],0) - 1);
                start++;
            }
            result = Math.max(result, i - start + 1);

        }
        return result != Integer.MIN_VALUE ? result : -1;
    }