前缀和,下次记住前缀和,从1开始存,cnt[0] 存0
class Solution {
public:
int findTheLongestSubstring(string s) {
int len = s.size();
vector<int>cntA(len+1, 0);
vector<int>cntE(len+1, 0);
vector<int>cntI(len+1, 0);
vector<int>cntO(len+1, 0);
vector<int>cntU(len+1, 0);
for(int i = 1; i <= len; i++)
{
cntA[i] = cntA[i-1] + (s[i-1] == 'a');
cntE[i] = cntE[i-1] + (s[i-1] == 'e');
cntI[i] = cntI[i-1] + (s[i-1] == 'i');
cntO[i] = cntO[i-1] + (s[i-1] == 'o');
cntU[i] = cntU[i-1] + (s[i-1] == 'u');
}
int res = 0;
for(int i = len; i > 0; i--)
{
for(int j = 0; j < i; j++)
{
if(i - j < res)
{
break;
}
if((cntA[i] - cntA[j]) % 2 == 0 &&
(cntE[i] - cntE[j]) % 2 == 0 &&
(cntI[i] - cntI[j]) % 2 == 0 &&
(cntO[i] - cntO[j]) % 2 == 0 &&
(cntU[i] - cntU[j]) % 2 == 0 )
{
// cout<<"----------"<<endl;
// cout<<i<<" "<<j<<endl;
// cout<<cntA[i]<<" "<<cntA[j]<<endl;
// cout<<cntE[i]<<" "<<cntE[j]<<endl;
// cout<<cntI[i]<<" "<<cntI[j]<<endl;
// cout<<cntO[i]<<" "<<cntO[j]<<endl;
// cout<<cntU[i]<<" "<<cntU[j]<<endl;
res = i - j;
// cout<<res<<endl;
}
}
}
return res;
}
};
教训:下面代码未通过
class Solution {
public:
int findTheLongestSubstring(string s) {
int len = s.size();
vector<int>cntA(len, 0);
vector<int>cntE(len, 0);
vector<int>cntI(len, 0);
vector<int>cntO(len, 0);
vector<int>cntU(len, 0);
cntA[0] = (s[0] == 'a');
cntE[0] = (s[0] == 'e');
cntI[0] = (s[0] == 'i');
cntO[0] = (s[0] == 'o');
cntU[0] = (s[0] == 'u');
for(int i = 1; i < len; i++)
{
cntA[i] = cntA[i-1] + (s[i] == 'a');
cntE[i] = cntE[i-1] + (s[i] == 'e');
cntI[i] = cntI[i-1] + (s[i] == 'i');
cntO[i] = cntO[i-1] + (s[i] == 'o');
cntU[i] = cntU[i-1] + (s[i] == 'u');
}
int res = 0;
for(int i = len-1; i >= 0; i--)
{
for(int j = 0; j < i; j++)
{
if(i - j + 1 < res)
{
break;
}
if((cntA[i] - cntA[j]) % 2 == 0 &&
(cntE[i] - cntE[j]) % 2 == 0 &&
(cntI[i] - cntI[j]) % 2 == 0 &&
(cntO[i] - cntO[j]) % 2 == 0 &&
(cntU[i] - cntU[j]) % 2 == 0 )
{
res = i - j + 1;
}
}
}
return res;
}
};