C++中計算與英語字母距離相同的字元對數量


給定一個字元字串,任務是計算字元對的數量,這些字元對在英語字母表中的距離與它們在字串中的距離相同。

輸入 − 字串 str = ‘Tutorials Point’

輸出 − 與英語字母表中距離相同的字元對的數量為:5

解釋 − 與英語字母表中距離相同的字元對是 (u, t), (u, r), (t, r), (i, o) 和 (s, n)。總共有 5 對。

輸入 − 字串 str = ‘Learning is the best habit’

輸出 − 與英語字母表中距離相同的字元對的數量為:12

解釋 − 與英語字母表中距離相同的字元對是 (r, i), (r, h), (n, i), (n, b), (i, g), (n, t), (g, i), (i, b), (s, h), (h, t), (s, t) 和 (a, b)。總共有 12 對。

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

  • 輸入字元字串並將資料傳遞給函式

  • 使用臨時變數 count 儲存可以形成的對的總數

  • 使用 length() 函式計算字串的長度

  • 從 i = 0 開始迴圈到字串長度

  • 在迴圈內,從 j = i+1 開始另一個迴圈到字串長度

  • 在迴圈內,將 temp 設定為 abs(str[i] - str[j])

  • 如果 temp = abs(i-j),則將 count 加 1

  • 返回 count

  • 列印結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int pairs_distance(string str){
   int count = 0;
   int len = str.length();
   for (int i = 0; i < len; i++){
      for (int j = i + 1; j < len; j++){
         int temp = abs(str[i] - str[j]);
         if (temp == abs(i - j)){
            count++;
         }
      }
   }
   return count;
}
int main(){
   string str = "Tutorials Point";
   cout<<"Count of character pairs at same distance as in English alphabets are: "<<pairs_distance(str);
   return 0;
}

輸出

如果執行以上程式碼,將生成以下輸出:

Count of character pairs at same distance as in English alphabets are: 5

更新於: 2020年11月2日

瀏覽量:115

開啟您的職業生涯

完成課程獲得認證

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