Advertisement
asdfg0998

dsfsfd

Sep 19th, 2024
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. // Function to calculate the length of the longest substring
  7. // with at most k replacements
  8. int characterReplacement(string s, int k) {
  9.     // Frequency array to count occurrences of each character
  10.     vector<int> freq(26, 0);
  11.    
  12.     int max_len = 0;  // Stores the maximum length of the substring
  13.     int max_freq = 0; // Stores the frequency of the most common character in the window
  14.     int start = 0;    // Left pointer for the sliding window
  15.  
  16.     // Iterate over the string with the 'end' pointer
  17.     for (int end = 0; end < s.size(); ++end) {
  18.         // Increment the frequency of the current character
  19.         freq[s[end] - 'A']++;
  20.        
  21.         // Update the max frequency in the current window
  22.         max_freq = max(max_freq, freq[s[end] - 'A']);
  23.        
  24.         // If the number of replacements required exceeds 'k', move the 'start' pointer
  25.         while (end - start + 1 - max_freq > k) {
  26.             freq[s[start] - 'A']--; // Decrease the frequency of the character being removed
  27.             start++; // Move the window to the right
  28.         }
  29.  
  30.         // Update the maximum length of the valid window
  31.         max_len = max(max_len, end - start + 1);
  32.     }
  33.    
  34.     return max_len;
  35. }
  36.  
  37. int main() {
  38.     // Test case 1
  39.     string s1 = "ABAB";
  40.     int k1 = 2;
  41.     cout << "Test Case 1: " << characterReplacement(s1, k1) << endl; // Expected output: 4
  42.  
  43.     // Test case 2
  44.     string s2 = "AABABBA";
  45.     int k2 = 1;
  46.     cout << "Test Case 2: " << characterReplacement(s2, k2) << endl; // Expected output: 4
  47.  
  48.     return 0;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement