Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- using namespace std;
- // Function to calculate the length of the longest substring
- // with at most k replacements
- int characterReplacement(string s, int k) {
- // Frequency array to count occurrences of each character
- vector<int> freq(26, 0);
- int max_len = 0; // Stores the maximum length of the substring
- int max_freq = 0; // Stores the frequency of the most common character in the window
- int start = 0; // Left pointer for the sliding window
- // Iterate over the string with the 'end' pointer
- for (int end = 0; end < s.size(); ++end) {
- // Increment the frequency of the current character
- freq[s[end] - 'A']++;
- // Update the max frequency in the current window
- max_freq = max(max_freq, freq[s[end] - 'A']);
- // If the number of replacements required exceeds 'k', move the 'start' pointer
- while (end - start + 1 - max_freq > k) {
- freq[s[start] - 'A']--; // Decrease the frequency of the character being removed
- start++; // Move the window to the right
- }
- // Update the maximum length of the valid window
- max_len = max(max_len, end - start + 1);
- }
- return max_len;
- }
- int main() {
- // Test case 1
- string s1 = "ABAB";
- int k1 = 2;
- cout << "Test Case 1: " << characterReplacement(s1, k1) << endl; // Expected output: 4
- // Test case 2
- string s2 = "AABABBA";
- int k2 = 1;
- cout << "Test Case 2: " << characterReplacement(s2, k2) << endl; // Expected output: 4
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement