C語言中任意兩個相同字元之間的最大字元數


給定一個字母字串。該陣列至少可以包含兩個相同字元的出現。這裡的任務是找到任意兩個字元出現之間最大數量的字元。如果沒有任何字元重複,則返回 -1。

輸入 − 字串 str = “abcdba”

輸出 − 字串中任意兩個相同字元之間的最大字元數 − 4

解釋 − 重複字元只有 'a' 和 'b',索引為:

1. 2‘a’ first index 0 last 5 , characters in between 5-0-1=4
2. ‘b’ first index 1 last 4 , characters in between 4-1-1=2
   Maximum character in between repeating alphabets : 4

輸入 − 字串 str = “AbcAaBcbC”

輸出 − 字串中任意兩個相同字元之間的最大字元數 − 5

解釋 − 重複字元只有 'A'、'b'、'c',索引為:

1. ‘A’ first index 0 last 3 , characters in between 3-0-1=2
2. ‘b’ first index 1 last 7 , characters in between 7-1-1=5
3. ‘c’ first index 2 last 6 , characters in between 6-2-1=3
   Maximum character in between repeating alphabets : 5

注意 − 如果輸入字串為“abcdefg”,則沒有重複字元,因此函式將返回 -1。

下面程式中使用的方法如下

  • 我們使用字元陣列將字串儲存為 Str[]

  • 函式 maxChars(char str[], int n) 用於計算任意兩個重複字母之間最大數量的字元。

  • 我們將變數 maxC 初始化為 -1。

  • 在 for 迴圈中,從開頭遍歷字串陣列。

  • 在巢狀 for 迴圈中,遍歷其餘字元並搜尋是否有重複。(如果 (str[i] == str[j])。

  • 如果為真,則透過減去索引來計算字元之間的差值。(temp=j-i-1)

  • 如果該值是迄今為止找到的最大值,則將其儲存在 maxC 中。

  • 遍歷整個字串後返回 maxC。

示例

 線上演示

#include <stdio.h>
#include <stdio.h>
#include <math.h>
int maxChars(char str[],int n){
   int size = n;
   int maxC = -1;
   for (int i = 0; i < n - 1; i++)
      for (int j = i + 1; j < n; j++)
         if (str[i] == str[j]){
            int temp=abs(j-i-1);
            maxC = maxC>temp?maxC:temp;
         }
   return maxC;
}
// Driver code
int main(){
   char Str[] = "AbcAaBcbC";
   printf("Maximum number of characters between any two same character in a string :%d",
   maxChars(Str,9) );
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Maximum number of characters between any two same character in a string : 5

更新於:2020年8月14日

1K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告