RainX_69

Find the Longest Substring Containing Vowels in Even Counts | TRICKY | MUST DO

Apr 4th, 2023
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | Source Code | 0 0
  1. https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/
  2.  
  3. Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
  4.  
  5. Example 1:
  6. Input: s = "eleetminicoworoep"
  7. Output: 13
  8. Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.
  9.  
  10. Example 2:
  11. Input: s = "leetcodeisgreat"
  12. Output: 5
  13. Explanation: The longest substring is "leetc" which contains two e's.
  14.  
  15. Example 3:
  16. Input: s = "bcbcbc"
  17. Output: 6
  18. Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.
  19.  
  20.  
  21. Constraints:
  22. 1 <= s.length <= 5 x 10^5
  23. s contains only lowercase English letters.
  24.  
  25. --------------------------------------------------------------------------------------------------------------------
  26.  
  27. Idea is that XOR of aeiou will always lead to 0 since even count will be cancelled in XOR
  28.  
  29. class Solution {
  30. public:
  31.    int findTheLongestSubstring(string s) {
  32.        unordered_map<int,int> mpp;
  33.        int prefixXOR=0;
  34.        int res=0;
  35.        for(int i=0;i<s.size();i++){
  36.            char x=s[i];
  37.            if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u'){
  38.                prefixXOR^=(1<<(x-'a'));
  39.            }
  40.            if(prefixXOR==0){
  41.                res=i+1;
  42.            }
  43.            if(mpp.find(prefixXOR)!=mpp.end()){
  44.                res=max(res,i-mpp[prefixXOR]);
  45.            }
  46.            if(mpp.find(prefixXOR)==mpp.end()){
  47.                mpp[prefixXOR]=i;
  48.            }
  49.        }
  50.        return res;
  51.    }
  52. };
Advertisement
Add Comment
Please, Sign In to add comment