Swap For Longest Repeated Character Substring
Given a string text
, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.
Example 1:
Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa", which its length is 3.
Example 2:
Input: text = "aaabaaa"
Output: 6
Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa", which its length is 6.
Example 3:
Input: text = "aaabbaaa"
Output: 4
Example 4:
Input: text = "aaaaa"
Output: 5
Explanation: No need to swap, longest repeated character substring is "aaaaa", length is 5.
Example 5:
Input: text = "abcdef"
Output: 1
Constraints:
1 <= text.length <= 20000
text
consist of lowercase English characters only.
/*
At each character, check if it is the same as the previous character.
If yes, Increment curr counter by 1.
If no, Try to skip one character and continue expanding.
If curr counter is less than the total number of occurences of character in
entire string, increment curr counter by 1.
Answer = max(Answer, curr counter)
*/
class Solution {
public int maxRepOpt1(String text){
StringBuilder str=new StringBuilder(text);
return Math.max(helper(text),helper(str.reverse().toString()));
}
public int helper(String text) {
HashMap<Character, Integer> map = new HashMap<>();
for (char c : text.toCharArray())
map.put(c, map.getOrDefault(c, 0) + 1);
int currCount = 0, maxLen = 0;
char previousChar = ' ';
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == previousChar)
currCount++;
else {
// if all the occurrences of the previousChar are not covered
// then we can try to skip one char and look for remaining continuously
if (map.containsKey(previousChar) && currCount != map.get(previousChar)) {
// Increasing count by 1 assuming that we will swap ith char with remaining
// previousChar's occurrences
currCount++;
int j = i + 1;
while (j < text.length() && text.charAt(j++) == previousChar)
currCount++;
// If all the remaining previousChar's occurrences are
// continously present after ith char
// then we will overshoot by 1,
// because we are increasing by 1 in the starting of this loop
if (currCount == map.get(previousChar) + 1)
currCount--;
}
maxLen = Math.max(maxLen, currCount);
// Resetting for the new character
currCount = 1;
previousChar = text.charAt(i);
}
maxLen = Math.max(maxLen, currCount);
}
return maxLen;
}
}
Last updated