最長的指定瑕疵度的元音子串


 

 

思路:

采用雙指針方法遍歷字符串;

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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM