给你若干个字符串,请编程输出每个字符串的子串个数。 输入 若干个字符串,每个字符串占一行,字符串中不含空格,长度最大为1000。 输出 对应每一行的字符串,输出该字符串子串的个数。 请使用c++语言。样例输入 复制 abc apple software 样例输出 复制 7 16 37
时间: 2024-03-21 20:40:11 浏览: 15
可以使用暴力枚举的方式来计算每个字符串的子串个数。具体地,对于每个字符串,枚举其所有可能的子串,然后统计子串的个数即可。时间复杂度为 O(n^3),其中 n 为字符串的长度。
以下是一个参考实现:
```c++
#include <iostream>
#include <string>
using namespace std;
int count_substrings(string s) {
int n = s.size(), cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
cnt++;
}
}
return cnt;
}
int main() {
string s;
while (cin >> s) {
cout << count_substrings(s) << endl;
}
return 0;
}
```
这个实现中,`count_substrings` 函数用来计算一个字符串的子串个数。它通过双重循环枚举所有可能的子串,然后累加个数。在 `main` 函数中,我们可以反复读入输入,对于每个字符串,调用 `count_substrings` 函数并输出结果。
相关问题
给你若干个字符串 请编程输出每个字符串的子串个数
好的,我可以为您编写这样的程序。以下是 Python 代码示例:
```python
def count_substrings(s):
n = len(s)
count = 0
for i in range(n):
for j in range(i+1, n+1):
count += 1
return count
strings = ["abc", "hello", "world"]
for s in strings:
print("The number of substrings in", s, "is", count_substrings(s))
```
该程序中,`count_substrings` 函数用于计算给定字符串的子串个数。它通过枚举所有可能的子串来计数。具体来说,对于字符串 `s`,它从第一个字符开始,枚举所有长度大于等于 1 且小于等于 `n` 的子串,其中 `n` 是字符串的长度。对于每个子串,它将计数器加 1。最后,它返回计数器的值。
在程序的主体部分,我们定义了一个字符串列表 `strings`,并使用 `count_substrings` 函数来计算每个字符串的子串个数。输出结果将显示在屏幕上。
给你若干个字符串,请编程输出每个字符串的子串个数
以下是一个用 Python 编程输出若干个字符串子串个数的示例代码:
```python
def count_substrings(s):
subs = set()
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
sub = s[i:j]
subs.add(sub)
return len(subs)
strings = ["hello", "world", "programming", "language"]
for s in strings:
print(f"{s} has {count_substrings(s)} substrings.")
```
该程序定义了一个 `count_substrings` 函数,该函数接受一个字符串参数,并返回该字符串的子串数量。在函数内部,我们使用嵌套循环来遍历字符串中的所有子串,并将它们添加到一个集合中。由于集合只包含唯一元素,因此最后我们返回集合的大小作为子串数量。
在主程序中,我们使用一个字符串列表 `strings` 存储了若干个字符串,然后用一个循环遍历每个字符串,分别计算它们的子串数量并输出到控制台。计算子串数量的方法与前面的示例代码相同,即使用嵌套循环遍历字符串中的所有子串,并将它们添加到一个集合中,最后返回集合的大小。
注意,在实际应用中,如果字符串数量较大或字符串长度较长,计算子串数量的时间复杂度可能会很高,因此可能需要优化算法或使用并行计算等技术来加速计算过程。