最長的指定瑕疵度的母音子串
阿新 • • 發佈:2022-01-28
思路:
採用雙指標方法遍歷字串;
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; }