RainX_69

Swap For Longest Repeated Character Substring | OA LEVEL | TRICKY

Apr 4th, 2023
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | Source Code | 0 0
  1. https://leetcode.com/problems/swap-for-longest-repeated-character-substring/
  2.  
  3. You are given a string text. You can swap two of the characters in the text.
  4. Return the length of the longest substring with repeated characters.
  5.  
  6. Example 1:
  7. Input: text = "ababa"
  8. Output: 3
  9. 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.
  10.  
  11. Example 2:
  12. Input: text = "aaabaaa"
  13. Output: 6
  14. Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6.
  15.  
  16. Example 3:
  17. Input: text = "aaaaa"
  18. Output: 5
  19. Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.
  20.  
  21.  
  22. Constraints:
  23. 1 <= text.length <= 2 * 10^4
  24. text consists of lowercase English characters only.
  25.  
  26. -----------------------------------------------------------------------------------------------------------------------
  27.  
  28. class Solution {
  29. public:
  30.     int helper(string &s, char x){
  31.         int n=s.size();
  32.         int res=0;
  33.        
  34.         int countS=0; // number of characters in suffix
  35.         for(auto c: s){
  36.             countS+=(c==x);
  37.         }
  38.        
  39.         int wS=0;
  40.         int countP=0; // number of characters in prefix
  41.         int mismatch=0;
  42.        
  43.         for(int wE=0;wE<n;wE++){
  44.             mismatch+=(s[wE]!=x);
  45.             countS-=(s[wE]==x);
  46.             while(mismatch>1){
  47.                 countP+=(s[wS]==x);
  48.                 mismatch-=(s[wS]!=x);
  49.                 wS++;
  50.             }
  51.             if(countP>0 || countS>0 || mismatch==0){
  52.                 res=max(res,wE-wS+1);
  53.             }
  54.         }    
  55.        
  56.         return res;
  57.     }
  58.    
  59.     int maxRepOpt1(string text) {
  60.         int res=1;
  61.         for(int i=0;i<26;i++){
  62.             res=max(res,helper(text,i+'a'));
  63.         }
  64.         return res;
  65.     }
  66. };
Advertisement
Add Comment
Please, Sign In to add comment