Leetcode Longest Repeating Character Replacement problem solution YASH PAL, 31 July 2024 In this Leetcode Longest Repeating Character Replacement problem solution, You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations. Problem solution in Python. class Solution(object): def characterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int using the sliding window technique """ window_start = 0 longest_substring, most_repeated = 0 , 0 freq_map = {} for window_end in range(len(s)): curr_char = s[window_end] if curr_char not in freq_map: freq_map[curr_char] = 0 freq_map[curr_char] += 1 most_repeated = max(most_repeated, freq_map[curr_char]) if window_end - window_start + 1 - most_repeated > k: left_char = s[window_start] freq_map[left_char] -= 1 window_start += 1 longest_substring = max(longest_substring, window_end - window_start + 1) return longest_substring Problem solution in Java. public int characterReplacement(String s, int k) { int start=0; int longCharCount=0; Map<Character, Integer> map = new HashMap<>(); int maxLength=0; for(int end=0;end<s.length();end++){ char endchar = s.charAt(end); map.put(endchar, map.getOrDefault(endchar,0)+1); longCharCount = Math.max(longCharCount, map.get(endchar)); if(end-start+1-longCharCount >k){ char startChar=s.charAt(start); map.put(startChar, map.getOrDefault(startChar,0)-1); start++; } maxLength = Math.max(maxLength, end-start+1); } return maxLength; } Problem solution in C++. class Solution { public: int characterReplacement(string s, int k) { int size = s.size(); int ret = 0; vector<int> count(26, 0); int start = 0; int end = 0; int Freq = 0; for(; end<size; end++){ count[s[end]-'A'] += 1; Freq = max(Freq, count[s[end]-'A']); while((end-start+1)-Freq > k) { count[s[start]-'A'] -= 1; start += 1; } ret=max(ret,end-start+1); } return ret; } }; Problem solution in C. int characterReplacement(char * s, int k){ if(s[0]==0)return 0; int n=strlen(s); int max=0; int i; int diff=0; int *record=calloc(26,4); int l; for(i=0,l=0;i<n;i++){ if(++record[s[i]-'A']<=max){ if(diff==k){ record[s[l++]-'A']--; } else{ diff++; } } else { max++; } } return max+diff; } coding problems