与C ++中英文字母相同距离的字符对计数
我们给了一个字符串,任务是计算与我们在英语字母中具有相同距离的字符对的数量。
输入-字符串str='nhooo.com'
输出-与英语字母相同距离的字符对计数为:5
说明-与英语字母具有相同距离的字符对是(u,t),(u,r),(t,r),(i,o)和(s,n)。因此,总共有5对。
输入-字符串str='学习是最好的习惯'
输出-与英语字母相同距离的字符对计数为: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对。
以下程序中使用的方法如下
输入字符串并将数据传递给函数
进行临时变量计数以存储可以形成的对的总数
使用length()函数计算字符串的长度
从i到0开始循环直到字符串的长度
在循环内,从j到i+1开始另一个循环,直到字符串的长度
在循环内部,将temp设置为abs(str[i]-str[j])
检查IFtemp=abs(ij),然后将计数增加1
返回计数
打印结果。
示例
#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 = "nhooo.com";
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