C++ 中長度為 K 的由相同字元組成的子字串的最大數量
給定任務是找到長度為 **K** 的由相同字元組成的子字串的最大數量。給定一個字串 s 和另一個整數 **K**,我們必須計算大小為 **K** 且具有相同字元的子字串的出現次數。
在找到的子字串中,我們必須選擇出現次數最多的子字串。
現在讓我們用一個例子來理解我們必須做什麼 -
輸入
s = ”tuuxyyuuc”, K = 2
輸出
2
解釋
這裡長度為 2 且具有相同字元的子字串是:“uu” 和 “yy”,但如所見,“yy” 只出現 1 次,“uu” 出現 2 次。因此,輸出變為 2。
輸入
s = “hhigggff”, K = 3
輸出
1
下面程式中使用的方法如下
在 Max() 函式中,初始化 int ans = 0 來儲存最終答案,size = str.size() 來儲存字串的大小,並宣告 char c 來儲存我們需要檢查的字元。
從 j = 0 迴圈到 j < 26,並將 c = ‘a’ + j 設定為我們將檢查每個字元。
初始化變數 int CurrCh = 0 用於儲存包含當前字元的子陣列的出現次數。
從 i = 0 迴圈到 i <= size – K,並檢查 if (str[i] != c)。如果是,則新增 continue; 語句。
初始化 count = 0 來儲存當前字元的子陣列的長度。
建立一個 while 迴圈,條件為 (i < size && count != K && str[i] == c),並在迴圈內部遞增 i 和 **count**。在 while 迴圈外部將 i 減 1。
檢查 if (count == K)。如果是,則遞增 **CurrCh**。
關閉第二個 For 迴圈,並透過設定 ans = max(ans, CurrCh) 來更新 **ans** 的值。
最後關閉第一個 For 迴圈並返回 **ans**。
示例
#include <bits/stdc++.h> using namespace std; int Max(string str, int K){ int ans = 0, size = str.size(); char c; //Checking for all characters for (int j = 0; j < 26; j++){ c = 'a' + j; //checking for current character int CurrCh = 0; for (int i = 0; i <= size - K; i++){ if (str[i] != c) continue; //Counting the size of sub-string int count = 0; while (i < size && count != K && str[i] == c){ i++; count++; } i--; //Increment CurrCh if sub-string has length K if (count == K) CurrCh++; } //Update ans ans = max(ans, CurrCh); } return ans; } //main function int main(){ string str = "tuuuxyuuu"; int K = 3; cout << Max(str, K); return 0; }
輸出
2
廣告