为什么fun函数这样计算就可以得到子串数量?请解释得容易理解一点
时间: 2023-12-28 16:04:01 浏览: 31
当我们要求能被3整除的子串数量时,我们可以观察到以下规律:
1. 如果一个数字的余数是0,那么它本身就是能被3整除的。
2. 如果两个数字的余数之和是0,那么它们的和也是能被3整除的。
3. 如果三个数字的余数之和是0,那么它们的和也是能被3整除的。
基于这个观察,我们可以得出结论:对于长度为n的字符串,以每个位置为结束的子串中,能被3整除的子串数量为:
- 对于余数为0的数字,它们本身就是能被3整除的子串,所以数量为1。
- 对于余数为1的数字,如果前面有k个余数为0的数字,那么它们的和就是能被3整除的子串,所以数量为k。
- 对于余数为2的数字,如果前面有k个余数为0的数字,那么它们的和加上该数字就是能被3整除的子串,所以数量为k。
综上所述,我们可以得到以下公式:
- 对于余数为0的数字,能被3整除的子串数量为(t-1)*t/2,其中t表示连续出现的余数为0的数字个数。
- 对于余数为1和2的数字,能被3整除的子串数量为(t-1)*t/2,其中t表示连续出现的余数为1或2的数字个数。
所以,通过fun函数的计算,我们可以得到能被3整除的子串数量。
希望这样的解释能够更容易理解。如果还有其他问题,请随时提问。
相关问题
编写一个函数,接收一个字符串,统计其中任意两个及两个以上相邻字符相同的子串的个数。函数原型为:int fun(const char *str);
以下是一个实现此功能的C语言代码:
```c
#include <stdio.h>
#include <string.h>
int fun(const char *str) {
int len = strlen(str);
int count = 0;
for (int i = 0; i < len - 1; i++) {
int j = i + 1;
while (j < len && str[j] == str[i]) {
count++;
j++;
}
}
return count;
}
int main() {
char str[] = "aabbaaccbbdd";
int count = fun(str);
printf("任意两个及两个以上相邻字符相同的子串个数:%d\n", count);
return 0;
}
```
在上述代码中,`fun`函数接收一个字符串作为参数,遍历字符串中的每一个字符,对于每一个字符,从它的下一个字符开始往后查找,如果遇到与它相同的字符,就将计数器加1,并继续往后查找。最后返回计数器的值。
在主函数中,我们定义了一个字符串`str`,并调用`fun`函数统计其中任意两个及两个以上相邻字符相同的子串的个数,最后输出结果。
计算字符串中子串出现的次数。要求:用一个子函数subString()实现,参数为指向字符串和要查找的子串的指针,返回次数
。好的,这个问题是一个计算型问题,可以直接回答。下面是代码实现:
```
#include <iostream>
using namespace std;
int subString(char* str, char* substr) {
int count = 0;
int len_str = strlen(str);
int len_sub = strlen(substr);
for (int i = 0; i <= len_str - len_sub; i++) {
bool is_match = true;
for (int j = 0; j < len_sub; j++) {
if (*(str+i+j) != *(substr+j)) {
is_match = false;
break;
}
}
if (is_match == true) {
count++;
}
}
return count;
}
int main() {
char str[] = "I love programming, programming is fun!";
char substr[] = "ming";
int count = subString(str, substr);
cout << "The count of substring \"" << substr << "\" in string \"" << str << "\" is: " << count << endl;
return 0;
}
```
这个程序实现了一个名为`subString`的子函数,来计算字符串中子串出现的次数。主函数中以“programming”为例,输出了计算结果,即输出了子串“ming”在字符串“I love programming, programming is fun!”中出现的次数。希望这个回答能够解决你的问题。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)