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.