C++ 计算字符串中ASCII值差为K的字符对数目

C++ 计算字符串中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的字符对。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程