C++中兩個大寫字母之間最多不同的的小寫字母


給定任務是在給定的字串中找到兩個大寫字母之間存在最大數量的不同小寫字母。

讓我們用一個例子來理解我們必須做什麼:

輸入

str = “JKyubDoorG”

輸出

3

解釋

“yub”位於兩個大寫字母K和D之間,計數為3。

“oor”也位於兩個大寫字母D和G之間,計數為2,因為‘o’是重複的字母,我們正在尋找不同的字母。

因此,輸出為3。

輸入

str = “ABcefsTaRpaep”

輸出

4

下面程式中使用的演算法如下:

  • 在函式Max()中,初始化int **size** = s.length() 來儲存給定字串的長度。

  • 迴圈從i = 0到i<size,並檢查if (s[i] >= 'A' && s[i] <= 'Z')。如果是,則遞增 **I** 並中斷;

  • 初始化int **ans** = 0 來儲存最終答案,另一個數組cnt[26] = {0}。

  • 迴圈從i = 0到i<size,然後檢查if (s[i] >= 'A' && s[i] <= 'Z') 來檢查當前字母是否為大寫字母。如果是,則初始化int **CurrMax** = 0 來儲存當前最大值。

  • 迴圈從i = 0到i<26,並檢查if (cnt[i] > 0)。如果是,則遞增CurrMax。

  • 在for迴圈之外,透過ans = max(ans, CurrMax);更新 **ans**,並使用memset(cnt, 0, sizeof(cnt));重置cnt[]陣列。

  • 關閉上面的if()語句,並檢查if (s[i] >= 'a' && s[i] <= 'z')。如果是,則遞增cnt[s[i] - 'a']。

  • 關閉for迴圈並返回ans。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int Max(string s){
   int size = s.length();
   // Ignore the lowercase alphabets in beginning
   for (int i = 0; i < size; i++){
      if (s[i] >= 'A' && s[i] <= 'Z'){
         i++;
         break;
      }
   }
   int ans = 0;
   int cnt[26] = { 0 };
   for (int i = 0; i < size; i++) {
      // If alphabet is uppercase,
      if (s[i] >= 'A' && s[i] <= 'Z'){
         //Counting all lower case
         //distinct alphabets
         int CurrMax = 0;
         for (int i = 0; i < 26; i++){
            if (cnt[i] > 0)
               CurrMax++;
         }
         // Update ans
         ans = max(ans, CurrMax);
         // Reset count array
         memset(cnt, 0, sizeof(cnt));
      }
      // If alphabet is lowercase
      if (s[i] >= 'a' && s[i] <= 'z')
         cnt[s[i] - 'a']++;
   }
   return ans;
}
// Driver function
int main(){
   string str = "JKyubDoorG";
   cout << Max(str);
   return 0;
}

輸出

3

更新於:2020年8月4日

239 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.