返回介绍

solution / 1300-1399 / 1371.Find the Longest Substring Containing Vowels in Even Counts / README_EN

发布于 2024-06-17 01:03:20 字数 3990 浏览 0 评论 0 收藏 0

1371. Find the Longest Substring Containing Vowels in Even Counts

中文文档

Description

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.

 

Example 1:

Input: s = "eleetminicoworoep"
Output: 13
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.

Example 2:

Input: s = "leetcodeisgreat"
Output: 5
Explanation: The longest substring is "leetc" which contains two e's.

Example 3:

Input: s = "bcbcbc"
Output: 6
Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.

 

Constraints:

  • 1 <= s.length <= 5 x 10^5
  • s contains only lowercase English letters.

Solutions

Solution 1

class Solution:
  def findTheLongestSubstring(self, s: str) -> int:
    pos = [inf] * 32
    pos[0] = -1
    vowels = 'aeiou'
    state = ans = 0
    for i, c in enumerate(s):
      for j, v in enumerate(vowels):
        if c == v:
          state ^= 1 << j
      ans = max(ans, i - pos[state])
      pos[state] = min(pos[state], i)
    return ans
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;
  }
}
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;
  }
};
func findTheLongestSubstring(s string) int {
  pos := make([]int, 32)
  for i := range pos {
    pos[i] = math.MaxInt32
  }
  pos[0] = -1
  vowels := "aeiou"
  state, ans := 0, 0
  for i, c := range s {
    for j, v := range vowels {
      if c == v {
        state ^= (1 << j)
      }
    }
    ans = max(ans, i-pos[state])
    pos[state] = min(pos[state], i)
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文