题解 | #统计字符串中子串出现的次数#

统计字符串中子串出现的次数

https://www.nowcoder.com/practice/9eb684f845a446f3b121472de2ea75cd

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

int my_count(const char* str, const char* substr, int n, int m) {
    int count = 0;
    int index = 0;
    bool flag = false;

    for (int i = 0; i < m; i++) {

        for (int j = 0; j < n; j++) {

            if (substr[i] == str[j]) {
                for (int k = 1; k < m; k++) {
                    if (substr[i + k] == str[j + k] && substr[i + k] != 0 && str[j + k] != 0) {
                        index++;
                        if (index == m - 1) {
                            flag = true ;
                            index = 0;
                        }
                    } else {
                        index = 0;
                        flag = false;
                    }
                }
                if (flag) {
                    count++;
                }
            }

        }
    }
    return count;
}

int main() {

    char str[100] = { 0 };
    char substr[100] = { 0 };

    cin.getline(str, sizeof(str));
    cin.getline(substr, sizeof(substr));

    int count = 0;

    // write your code here......
    count = my_count(str, substr, strlen(str), strlen(substr));

    cout << count << endl;

    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务