Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://leetcode.com/problems/swap-for-longest-repeated-character-substring/
- You are given a string text. You can swap two of the characters in the text.
- Return 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" with length 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" with length 6.
- Example 3:
- Input: text = "aaaaa"
- Output: 5
- Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.
- Constraints:
- 1 <= text.length <= 2 * 10^4
- text consists of lowercase English characters only.
- -----------------------------------------------------------------------------------------------------------------------
- class Solution {
- public:
- int helper(string &s, char x){
- int n=s.size();
- int res=0;
- int countS=0; // number of characters in suffix
- for(auto c: s){
- countS+=(c==x);
- }
- int wS=0;
- int countP=0; // number of characters in prefix
- int mismatch=0;
- for(int wE=0;wE<n;wE++){
- mismatch+=(s[wE]!=x);
- countS-=(s[wE]==x);
- while(mismatch>1){
- countP+=(s[wS]==x);
- mismatch-=(s[wS]!=x);
- wS++;
- }
- if(countP>0 || countS>0 || mismatch==0){
- res=max(res,wE-wS+1);
- }
- }
- return res;
- }
- int maxRepOpt1(string text) {
- int res=1;
- for(int i=0;i<26;i++){
- res=max(res,helper(text,i+'a'));
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment