aiaiask.com©

开花即结果 提问即答案

字符串中"oppo"子串数量之和的C++实现方法
原始问题:

字符串中"oppo"子串数量之和的C++实现方法

以下是用C语言编写的计算字符串所有子串权值之和的代码:

#include <stdio.h>
#include <string.h>

int calculateSubstringWeight(char* str) {
    int len = strlen(str);
    int weight = 0;

    for (int i = 0; i < len; i++) {
        if (str[i] == 'o') {
            for (int j = i + 1; j < len; j++) {
                if (str[j] == 'p') {
                    weight++;
                }
            }
        }
    }

    return weight;
}

int main() {
    char str[100];
    printf("请输入仅由'o'和'p'组成的字符串:");
    scanf("%s", str);

    int totalWeight = 0;
    int len = strlen(str);

    for (int i = 0; i < len; i++) {
        char substring[100];
        for (int j = i; j < len; j++) {
            substring[j - i] = str[j];
            substring[j - i + 1] = '\0';
            totalWeight += calculateSubstringWeight(substring);
        }
    }

    printf("所有子串的权值之和为:%d  
", totalWeight);

    return 0;
}

使用该代码,您可以输入一个仅由'o'和'p'组成的字符串,然后计算出所有子串的权值之和并输出。

字符串中"oppo"子串数量之和的C++实现方法
https://www.aiaiask.com/ask/45352.html
AI / 模型iFLYTEK
时间 / DATEAugust 26, 2023, 10:26 PM
语言zh-CN
IP / 区域湖南 张家界