📌  相关文章
📜  查找长度为 k 且字符的 ASCII 值之和可被 k 整除的子串的数量

📅  最后修改于: 2022-05-13 01:57:05.879000             🧑  作者: Mango

查找长度为 k 且字符的 ASCII 值之和可被 k 整除的子串的数量

给定一个字符串和一个数字k ,任务是找到长度为 k 且字符的 ASCII 值之和可被 k 整除的子字符串的数量。

例子:

方法:首先,我们找到长度为 k 的第一个子串的字符的 ASCII 值之和,然后使用滑动窗口技术减去前一个子串的第一个字符的 ASCII 值并加上当前字符的 ASCII 值。如果 sum 可以被 k 整除,我们将在每一步增加计数器。

以下是上述方法的实现:

C++
// C++ program to find number of substrings
// of length k whose sum of ASCII value of
// characters is divisible by k
#include
using namespace std;
 
int count(string s, int k)
{
     
    // Finding length of string
    int n = s.length();
    int d = 0 ,i;
    int count = 0 ;
     
    for (i = 0; i 


Java
// Java program to find number of substrings
// of length k whose sum of ASCII value of
// characters is divisible by k
 
 
public class GFG{
 
    static int count(String s, int k){
     
    // Finding length of string
    int n = s.length() ;
    int d = 0 ,i;
    int count = 0 ;
     
    for (i = 0; i 


Python3
# Python3 program to find number of substrings
# of length k whose sum of ASCII value of
# characters is divisible by k
 
def count(s, k):
     
    # Finding length of string
    n = len(s)
    d, count = 0, 0
    for i in range(k):
         
        # finding sum of ASCII value of first
        # substring
        d += ord(s[i])
        if (d % k == 0):
            count += 1
            for i in range(k, n):
                 
                # Using sliding window technique to
                # find sum of ASCII value of rest of
                # the substring
                prev = ord(s[i-k])
                d -= prev
                d += ord(s[i])
                 
                # checking if sum is divisible by k
                if (d % k == 0):
                    count += 1
                    return count
# Driver code
s = "bcgabc"
k = 3
ans = count(s, k)
print(ans)


C#
// C# program to find number of substrings
// of length k whose sum of ASCII value of
// characters is divisible by k
  
  
using System;
public class GFG{
  
    static int count(string s, int k){
      
    // Finding length of string
    int n = s.Length ;
    int d = 0 ,i;
    int count = 0 ;
      
    for (i = 0; i 


Javascript


输出:
2