LeetCode 1156: Swap For Longest Repeated Character Substring Solution
Master LeetCode problem 1156 (Swap For Longest Repeated Character Substring), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1156. Swap For Longest Repeated Character Substring
Problem Explanation
Explanation
To solve this problem, we can iterate through the input string and keep track of the longest substring with repeated characters that can be obtained by swapping two characters. We can use a sliding window approach to find the longest substring with repeated characters.
-
Initialize variables:
maxLento store the maximum length of the repeated character substring.maxFreqto store the maximum frequency of any character in the current window.countto store the total count of characters in the current window.windowto store the frequency of characters in the current window.startto mark the start of the current window.
-
Iterate through the string:
- For each character in the string:
- Increment the frequency of the character in the window.
- Update
maxFreqwith the maximum frequency encountered so far. - Update
countwith the total count of characters in the current window. - While the condition
count - maxFreq > kis met:- Decrement the frequency of the character at index
start. - Increment
startto move the window.
- Decrement the frequency of the character at index
- Update
maxLenwith the maximum ofmaxLenandcount.
- For each character in the string:
-
Return the
maxLen.
Solution Code
class Solution {
public int characterReplacement(String s, int k) {
int[] window = new int[26];
int maxLen = 0, maxFreq = 0, start = 0, count = 0;
for (int end = 0; end < s.length(); end++) {
maxFreq = Math.max(maxFreq, ++window[s.charAt(end) - 'A']);
count++;
while (count - maxFreq > k) {
window[s.charAt(start) - 'A']--;
start++;
}
maxLen = Math.max(maxLen, count);
}
return maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1156 (Swap For Longest Repeated Character Substring)?
This page provides optimized solutions for LeetCode problem 1156 (Swap For Longest Repeated Character Substring) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1156 (Swap For Longest Repeated Character Substring)?
The time complexity for LeetCode 1156 (Swap For Longest Repeated Character Substring) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1156 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1156 in Java, C++, or Python.