Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวนซับสตริงความยาว n ที่สร้างได้จากสตริงที่กำหนดใน C++


เราได้รับสตริง str[] และตัวเลข n เป้าหมายคือหาซับสตริงทั้งหมดของ str[] ที่มีความยาว n หากสตริงคือ "abcde" และ n=3 ซับสตริงความยาว 3 คือ "abc", "bcd", "cde" จำนวนคือ 3

มาดูตัวอย่าง

อินพุต − str[] = "computer" n=4

เอาต์พุต − จำนวนซับสตริงความยาว n ที่สร้างได้จากสตริงที่กำหนด คือ 5

คำอธิบาย − ซับสตริงความยาว 4 คือ: "comp", "ompu", "mput", "pute", "uter"

อินพุต − str[] = "development" n=5

เอาต์พุต − จำนวนซับสตริงความยาว n ที่สร้างได้จากสตริงที่กำหนด คือ 7

คำอธิบาย − ซับสตริงความยาว 5 คือ: "devel", "evelo", "velop", "elopm", "lopme", "opmen", "pment"

แนวทางที่ใช้ในโปรแกรม

ถ้าเรานำความยาวของสตริง str[] เป็น L จำนวนซับสตริงความยาว n ภายใน str[] คือ L-n+1 หากสตริงคือ "abcdefghi" และ n เป็น 4 ซับสตริงจะเป็น "abcd", "bcde", "cdef", "defg", "efgh", "fghi" จำนวน 6 นอกจากนี้ 9-4+1=6

  • รับสตริง str
  • รับ n เป็นจำนวนเต็ม
  • ฟังก์ชัน possible_substring(string str, int length, int n) รับสตริง ความยาว และ n คืนจำนวนซับสตริงของ str ที่มีความยาว n
  • ตัวแปร count
  • กำหนด count = length-n+1
  • คืน count เป็นผลลัพธ์

ตัวอย่างโค้ด C++

#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;
}

เอาต์พุต

หากรันโค้ดด้านบนจะได้ผลลัพธ์ดังนี้ −

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