LeetCode 2213: Longest Substring of One Repeating Character Solution
Master LeetCode problem 2213 (Longest Substring of One Repeating Character), a hard 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.
2213. Longest Substring of One Repeating Character
Problem Explanation
Explanation
To solve this problem, we can iterate over the queries one by one and update the string accordingly. After each update, we can find the length of the longest substring consisting of only one repeating character by maintaining a count of consecutive characters. Whenever we encounter a different character, we update the count and store the maximum length found so far.
Algorithm
- Initialize a result array to store the lengths of longest substrings after each query.
- Iterate over each query.
- Update the character at the specified index in the string.
- Initialize variables to keep track of the current character, count of consecutive characters, and maximum length found so far.
- Iterate through the string and update the count and maximum length accordingly.
- Update the result array with the maximum length found after each query.
- Return the result array.
Time Complexity
The time complexity of this solution is O(n * k), where n is the length of the string and k is the number of queries.
Space Complexity
The space complexity is O(n) to store the result array.
Solution Code
class Solution {
public int[] longestSubsequence(String s, String queryCharacters, int[] queryIndices) {
int[] lengths = new int[queryIndices.length];
char[] str = s.toCharArray();
for (int i = 0; i < queryIndices.length; i++) {
str[queryIndices[i]] = queryCharacters.charAt(i);
lengths[i] = getLongestSubstringLength(str);
}
return lengths;
}
private int getLongestSubstringLength(char[] str) {
int maxLen = 0;
int count = 1;
for (int i = 1; i < str.length; i++) {
if (str[i] == str[i - 1]) {
count++;
} else {
maxLen = Math.max(maxLen, count);
count = 1;
}
}
return Math.max(maxLen, count);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2213 (Longest Substring of One Repeating Character)?
This page provides optimized solutions for LeetCode problem 2213 (Longest Substring of One Repeating Character) 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 2213 (Longest Substring of One Repeating Character)?
The time complexity for LeetCode 2213 (Longest Substring of One Repeating Character) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2213 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2213 in Java, C++, or Python.