File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ fn longest_uniform_substring_after_replacements ( s : String , k : i32 ) -> i32 {
2
+ use std:: collections:: HashMap ;
3
+
4
+ let mut freqs = HashMap :: new ( ) ;
5
+ let mut highest_freq = 0 ;
6
+ let mut max_len = 0 ;
7
+ let mut left = 0 ;
8
+ let mut right = 0 ;
9
+ let s = s. as_bytes ( ) ;
10
+
11
+ while right < s. len ( ) {
12
+ // Update the frequency of the character at the right pointer
13
+ // and the highest frequency for the current window.
14
+ * freqs. entry ( s[ right] ) . or_insert ( 0 ) += 1 ;
15
+ highest_freq = highest_freq. max ( * freqs. get ( & s[ right] ) . unwrap ( ) ) ;
16
+ // Calculate replacements needed for the current window.
17
+ let num_chars_to_replace = ( ( right - left + 1 ) as i32 ) - highest_freq;
18
+ // Slide the window if the number of replacements needed exceeds
19
+ // 'k'. The right pointer always gets advanced, so we just need
20
+ // to advance 'left'.
21
+ if num_chars_to_replace > k {
22
+ // Remove the character at the left pointer from the hash map
23
+ // before advancing the left pointer.
24
+ * freqs. get_mut ( & s[ left] ) . unwrap ( ) -= 1 ;
25
+ left += 1 ;
26
+ }
27
+ // Since the length of the current window increases or stays the
28
+ // same, assign the length of the current window to 'max_len'.
29
+ max_len = max_len. max ( right - left + 1 ) ;
30
+ // Expand the window.
31
+ right += 1 ;
32
+ }
33
+
34
+ max_len as i32
35
+ }
You can’t perform that action at this time.
0 commit comments