File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ fun longestUniformSubstringAfterReplacements (s : String , k : Int ): Int {
2
+ val freqs = mutableMapOf<Char , Int >()
3
+ var highestFreq = 0
4
+ var maxLen = 0
5
+ var left = 0
6
+ var right = 0
7
+ while (right < s.length) {
8
+ // Update the frequency of the character at the right pointer
9
+ // and the highest frequency for the current window.
10
+ freqs[s[right]] = freqs.getOrDefault(s[right], 0 ) + 1
11
+ highestFreq = maxOf(highestFreq, freqs[s[right]]!! )
12
+ // Calculate replacements needed for the current window.
13
+ val numCharsToReplace = (right - left + 1 ) - highestFreq
14
+ // Slide the window if the number of replacements needed exceeds
15
+ // 'k'. The right pointer always gets advanced, so we just need
16
+ // to advance 'left'.
17
+ if (numCharsToReplace > k) {
18
+ // Remove the character at the left pointer from the hash map
19
+ // before advancing the left pointer.
20
+ freqs[s[left]] = freqs[s[left]]!! - 1
21
+ left++
22
+ }
23
+ // Since the length of the current window increases or stays the
24
+ // same, assign the length of the current window to 'maxLen'.
25
+ maxLen = right - left + 1
26
+ // Expand the window.
27
+ right++
28
+ }
29
+ return maxLen
30
+ }
You can’t perform that action at this time.
0 commit comments