在 C++ 中查詢包含偶數個母音的最長子字串
假設我們有字串 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]]% 2
如果 m 有 temp,則 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP