在C ++中找到偶数个包含元音的最长子串

假设我们有字符串s,我们必须找到包含每个元音的偶数次的最长子字符串的大小。也就是说,“ a”,“ e”,“ i”,“ o”和“ u”必须出现偶数次。因此,如果字符串类似于“ helloworld”,则输出为8。

为了解决这个问题,我们将遵循以下步骤-

  • ret:= 0,定义两个映射m和cnt,设置m [“ 00000”]:= -1

  • 将元音存储到元音数组中

  • 对于范围从0到s的i

    • x:= s [i],好的:= false

    • 将cnt [x]加1,设置temp:=空字符串

    • 对于0到4范围内的k:temp:= temp +'0'+ cnt [vowels [k]] mod 2

    • 如果m具有温度,则ret:= ret和i – m [temp]的最大值,否则m [temp]:= i

  • 返回ret

范例(C ++)

让我们看下面的实现以更好地理解-

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int findTheLongestSubstring(string s) {
      int ret = 0;
      map <string, int> m;
      map <char, int> cnt;
      m["00000"] = -1;
      char vowels[5] = {'a', 'e', 'i', 'o', 'u'};
      for(int i = 0; i < s.size(); i++){
         char x = s[i];
         bool ok = false;
         cnt[x]++;
         string temp = "";
         for(int k = 0; k < 5; k++){
            temp+= ('0' + (cnt[vowels[k]] % 2));
         }
         if(m.count(temp)){
            ret = max(ret, i - m[temp]);
         }
         else{
            m[temp] = i;
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.findTheLongestSubstring("helloworld"));
}

输入项

“helloworld”

输出结果

8