1371 - Find the Longest Substring Containing Vowels in Even Counts

 C++

  • class Solution {
    public:
        int findTheLongestSubstring(string s) {
            vector<int> pos(32, INT_MAX);
            pos[0] = -1;
            string vowels = "aeiou";
            int state = 0, ans = 0;
            for (int i = 0; i < s.size(); ++i) {
                for (int j = 0; j < 5; ++j)
                    if (s[i] == vowels[j])
                        state ^= (1 << j);
                ans = max(ans, i - pos[state]);
                pos[state] = min(pos[state], i);
            }
            return ans;
        }
    };

JAVA

  • class Solution {
    
        public int findTheLongestSubstring(String s) {
            int[] pos = new int[32];
            Arrays.fill(pos, Integer.MAX_VALUE);
            pos[0] = -1;
            String vowels = "aeiou";
            int state = 0;
            int ans = 0;
            for (int i = 0; i < s.length(); ++i) {
                char c = s.charAt(i);
                for (int j = 0; j < 5; ++j) {
                    if (c == vowels.charAt(j)) {
                        state ^= (1 << j);
                    }
                }
                ans = Math.max(ans, i - pos[state]);
                pos[state] = Math.min(pos[state], i);
            }
            return ans;
        }
    }

Comments