题目:
开头和结尾都是元音字母(aeiouAEIOU)的字符串为 元音字符串 ,其中混杂的非元音字母数量为其 瑕疵度 。比如:
· “a” 、 “aa”是元音字符串,其瑕疵度都为0
· “aiur”不是元音字符串(结尾不是元音字符)
· “abira”是元音字符串,其瑕疵度为2
现给定一个字符串,请找出指定瑕疵度的最长元音字符子串,并输出其长度,如果找不到满足条件的元音字符子串,输出0。
子串:字符串中任意个连续的字符组成的子序列称为该字符串的子串。
输入输出:
输入描述:
首行输入是一个整数,表示预期的瑕疵度flaw,取值范围[0, 65535]。
接下来一行是一个仅由字符a-z和A-Z组成的字符串,字符串长度(0, 65535]。
输出描述:
输出为一个整数,代表满足条件的元音字符子串的长度。
思路:
利用滑动窗口的思想
#include <iostream>
#include <string>
using namespace std;
//判断是否是元音函数
bool judgeVowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
return true;
}
return false;
}
int maxLen(string& str, int xcd) {
int max_len = 0;
int left = 0, right = 0, current_xcd = 0;
while (right < str.size()) {
if (!judgeVowel(str[right])) {
current_xcd++;
}
if (judgeVowel(str[left]) && judgeVowel(str[right]) && current_xcd == xcd) {
max_len = max(max_len, right - left + 1);
}
while (current_xcd > xcd) {
if (!judgeVowel(str[left])) {
current_xcd--;
}
left++;
}
right++;
}
return max_len;
}
int main() {
int xcd, len;
string str;
while (cin >> xcd >> str) {
cout << maxLen(str, xcd) << endl;
}
return 0;
}