You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[LeetCode] 1156. Swap For Longest Repeated Character Substring #1156
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.
class Solution {
public:
int maxRepOpt1(string text) {
int res = 0, n = text.size();
unordered_map<char, int> charCnt;
for (char c : text) ++charCnt[c];
for (int i = 0; i < n; ++i) {
char cur = text[i];
int j = i, cnt = 0, diff = 0;
while (j < n && (text[j] == cur || diff == 0) && cnt < charCnt[cur]) {
if (cur != text[j]) {
++diff;
i = j - 1;
}
++cnt;
++j;
}
res = max(res, cnt);
}
for (int i = n - 1; i >= 0; --i) {
char cur = text[i];
int j = i, cnt = 0, diff = 0;
while (j >= 0 && (text[j] == cur || diff == 0) && cnt < charCnt[cur]) {
if (cur != text[j]) {
++diff;
i = j + 1;
}
++cnt;
--j;
}
res = max(res, cnt);
}
return res;
}
};
Activity
[-][LeetCode] 1156. Missing Problem[/-][+][LeetCode] 1156. Swap For Longest Repeated Character Substring[/+]