在C ++中查找长度为k的子字符串数,其子字符串的ASCII值之和可被k整除
在这里,我们将看到另一个问题,其中给出了一个字符串和另一个整数值k。我们必须找到长度为k的子字符串的数量,其字符的ASCII值之和可被k整除。
假设一个字符串是“BCGABC”。并且k的值为3。在这里,字符串BCG的ASCII总和为300,ABC的ASCII总和为294,两者均可被k=3整除。
该方法很简单。首先,我们必须找到第一个子串字符的ASCII值,其长度为k。我们必须使用滑动窗口技术,减去窗口第一个字符的ASCII,然后加上滑动窗口后出现的下一个字符的ASCII,当总和可被k整除时,我们将在每一步增加计数。。
示例
#include <iostream>
using namespace std;
int countKLenSubstr(string str, int k) {
int len = str.length();
int sum = 0;
int count = 0 ;
for (int i = 0; i <len; i++)
sum += str[i] ; //ASCII sum of first substring
if (sum % k == 0)
count++;
for (int i = k; i < len; i++) {
int prev_ascii = str[i-k]; //ASCII of the first character of the window
sum -= prev_ascii;
sum += str[i];
if (sum % k == 0)
count += 1;
}
return count ;
}
int main() {
string s = "BCGABC" ;
int k = 3 ;
cout<<"Number of substrings: " << countKLenSubstr(s, k);
}输出结果
Number of substrings: 2
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬