统计字符串中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)。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
演示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的字符对。