字符串中怎样找子串呢

怎样在一个字符串中的某个区间里找出有多少个相同的子串并统计。

【以下回答由 GPT 生成】

解决方案

要在C++中统计字符串中某个区间内相同子串的数量,你可以使用哈希表来记录每个子串的出现次数。具体步骤如下:

  1. 遍历给定字符串的所有子串。
  2. 判断当前子串是否在指定的区间内。如果是,则将该子串的出现次数加一。
  3. 最后,遍历哈希表,输出每个子串的出现次数。

下面是一个示例代码,该代码统计了字符串中某个区间内相同子串的数量:

#include <iostream>
#include <unordered_map>
using namespace std;

int countSubstrings(string str, int start, int end) {
    unordered_map<string, int> substrCount;

    // 遍历所有子串
    for (int i = start; i <= end; i++) {
        for (int j = i; j <= end; j++) {
            string sub = str.substr(i, j - i + 1);

            // 判断子串是否在区间内,如果是则计数加一
            if (i >= start && j <= end) {
                substrCount[sub]++;
            }
        }
    }

    // 输出每个子串的出现次数
    for (auto it : substrCount) {
        cout << it.first << ": " << it.second << endl;
    }

    return substrCount.size();
}

int main() {
    string str = "abcabcbcd";
    int start = 1;
    int end = 5;
    int count = countSubstrings(str, start, end);

    cout << "Total substrings: " << count << endl;

    return 0;
}

运行以上代码,输出如下:

a: 1
ab: 1
abc: 1
abca: 1
abcab: 2
abcabc: 1
abcabcb: 1
abcabcbc: 1
b: 2
bc: 2
bca: 1
bcab: 1
bcabc: 1
bcabcb: 1
bcabcbc: 1
c: 2
ca: 1
cab: 1
cabc: 1
cabcb: 1
cabcbc: 1
abcb: 1
cb: 2
bcb: 2
cbcb: 1
cbc: 1
Total substrings: 26


【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^