最长的指定瑕疵度的元音子串
作者:互联网
思路:
采用双指针方法遍历字符串;
1)初始时左右边界指针都指向位置0;
2)边界判断:左元音右缺陷(right++)、左缺陷右元音(left++)、左右都缺陷(left++、right++)、左右都元音(计算缺陷度);
3)计算元音字串的长度:
1. 先判断当前缺陷度是否满足要求,小于则right++,大于则left++;
2. 缺陷度符合要求后,才计算当前字串长度,并和历史最大值比较,更新最大值。
#include <iostream> #include <string> using namespace std; int GetLongestFlawedVowelSubstrLen(const size_t flaw, const string& input) { int element[128] = {0}; element['a'] = 1; element['A'] = 1; element['e'] = 1; element['E'] = 1; element['i'] = 1; element['I'] = 1; element['o'] = 1; element['O'] = 1; element['u'] = 1; element['U'] = 1; int noeleCnt = 0; int length = input.length(); int left = 0; int right = 0; int maxLen = 0; int currentLen = 0; while (right < length) { if (!element[input[right]]) { noeleCnt++; right++; continue; } while (!element[input[left]]) { noeleCnt--; left++; } if (noeleCnt == flaw) { currentLen = right - left + 1; maxLen = currentLen > maxLen ? currentLen : maxLen; right++; } else if (noeleCnt < flaw) { right++; } else if (noeleCnt > flaw) { while (element[input[left]] == 1) { left++; } noeleCnt--; left++; } } return maxLen; } int main() { size_t flaw; cin >> flaw; string input; cin >> input; cout << GetLongestFlawedVowelSubstrLen(flaw, input) << endl; return 0; }
标签:子串,right,瑕疵,element,++,int,元音,input,left 来源: https://www.cnblogs.com/gcter/p/15851895.html