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

cc++server side programmingprogramming

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

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

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

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

  • 对于 i,范围为 0 到 s 的大小

    • x := s[i],并且 ok := false

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

    • 对于 k,范围为 0 到 4:temp := temp + ‘0’ + cnt[vowels[k]] mod 2

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

  • return 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

相关文章