Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Đếm số substring độ dài n từ chuỗi cho trước trong C++


Cho chuỗi str[] và số n. Tìm tất cả substring của str có độ dài n. Ví dụ: "abcde", n=3 → "abc", "bcd", "cde", count = 3.

Ví dụ

Đầu vào − str[] = "computer", n = 4

Đầu ra − 5

Giải thích − "comp", "ompu", "mput", "pute", "uter".

Đầu vào − str[] = "development", n = 5

Đầu ra − 7

Giải thích − "devel", "evelo", "velop", "elopm", "lopme", "opmen", "pment".

Phương pháp giải

Nếu độ dài chuỗi là L, số substring độ dài n là L - n + 1. Ví dụ "abcdefghi", n=4 → 6 substring, và 9-4+1=6.

  • Hàm possible_substring(string str, int length, int n).
  • count = length - n + 1.
  • Trả về count.

Ví dụ code

#include <bits/stdc++.h>
using namespace std;

int possible_substring(string str, int length, int n) {
    int count = length - n + 1;
    return count;
}

int main() {
    string str = "learning";
    int length = str.length();
    int n = 2;
    cout << "Count of substrings of length n possible from the given string are: " << possible_substring(str, length, n);
    return 0;
}

Đầu ra

Count of substrings of length n possible from the given string are: 7