Skip to content

1371. Find the Longest Substring Containing Vowels in Even Counts 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int findTheLongestSubstring(string s) {
    int ans = 0;
    int prefix = 0;  // binary prefix
    unordered_map<int, int> prefixToIndex{{0, -1}};

    for (int i = 0; i < s.length(); ++i) {
      const int index = string("aeiou").find(s[i]);
      if (index != -1)
        prefix ^= 1 << index;
      if (!prefixToIndex.count(prefix))
        prefixToIndex[prefix] = i;
      ans = max(ans, i - prefixToIndex[prefix]);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int findTheLongestSubstring(String s) {
    int ans = 0;
    int prefix = 0; // binary prefix
    Map<Integer, Integer> prefixToIndex = new HashMap<>();
    prefixToIndex.put(0, -1);

    for (int i = 0; i < s.length(); ++i) {
      final int index = "aeiou".indexOf(s.charAt(i));
      if (index != -1)
        prefix ^= 1 << index;
      prefixToIndex.putIfAbsent(prefix, i);
      ans = Math.max(ans, i - prefixToIndex.get(prefix));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def findTheLongestSubstring(self, s: str) -> int:
    ans = 0
    prefix = 0  # binary prefix
    prefixToIndex = {0: -1}

    for i, c in enumerate(s):
      index = 'aeiou'.find(c)
      if index != -1:
        prefix ^= 1 << index
      prefixToIndex.setdefault(prefix, i)
      ans = max(ans, i - prefixToIndex[prefix])

    return ans