統計字串中ASCII碼差值為K的字元對


在本教程中,我們將學習如何統計字串中ASCII碼差值為K的字元對。K是任意差值,可以是1或0。建立C++程式碼以統計輸入字串S中此類字元對。我們使用了String類的size()方法

語法

size() = It is a String class method. It is an empty parameter library method. It returns the size of the string in terms of bytes. 
string_name.size()
Example = s.size()

ASCII碼是為字元、符號和其他內容預定義的值,用於計算機理解。

用於統計ASCII碼差值為K(任何定義的值)的字元對的字串僅包含小寫字母。

演示1

考慮一個示例以瞭解問題的潛在關鍵概念。

String = “abcb”
K = 0

輸出

 = 1

給定字串中ASCII碼差值為0的字元對只有一個,該對是(b, b)。

演示2

String = “abcd”
K = 1

輸出

= 3

ASCII碼差值為1的字元對有3個,這些對是(a, b),(b, c),(c, d)。

演算法

  • 為字元的出現建立一個數組。

  • 當K = 0(僅在類似的重複字元中ASCII碼差值為0)時。使用公式:character[迴圈變數] * (character [迴圈變數] -1)/2新增計數

  • 當K = 1時。新增字元出現次數並將此值新增到計數變數。

  • 返回計數變數。

邏輯1示例

我們正在使用C++程式設計實現上述演算法。我們定義了一個countDifferencePairs()函式來計算所需對的數量。該函式將查詢ASCII碼差值為0的字元對。

我們使用宏MAX將其值定義為26,並且無論何時在程式中呼叫它,預處理器都會將MAX更改為26。

#include <bits/stdc++.h>
using namespace std;
#define MAX 26
 
//user-defined function to count the number of required pairs with K difference
int countDifferencePairs(string s, int x){
//This function returns the size of the string
   int l = s.size();
 
   //Storing the character frequency 
      int frq[MAX];
      memset(frq, 0, sizeof frq);
 
   for (int i = 0; i < l; i++)
      frq[s[i] - 'a']++;
 
   //counter variable to count the number of pairs
      int cp = 0;
 
   //If the condition to check the ASCII difference is 0 or not
      if (x == 0){
         for (int i = 0; i < MAX; i++)
            if (frq[i] > 1)
               cp += ((frq[i] * (frq[i] - 1)) / 2);
   }
   else {
      for (int i = 0; i < MAX; i++)
         if (frq[i] > 0 && i + x < MAX && frq[i + x] > 0)
            cp += (frq[i] * frq[i + x]);;
   }
   return cp;
}
 
// Controlling Part
int main(){
   string s = "abcda";
   int x = 0;
   cout <<"Pairs with given ascii values are:"<<  countDifferencePairs(s, x);
 
   return 0;
}

輸出

Pairs with given ascii values are: 1

結論

在本教程中,我們開發了一種方法來統計輸入字串中ASCII碼差值為K的字元對。K可以是任何值,在C++實現示例中,我們使用了0差值。我們使用了字串類的size()函式。在實現過程中,我們僅考慮了輸入字串中ASCII碼差值為0的字元對。

更新於: 2023年7月31日

105次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告