使用 C++ 查詢字串的子字串數量


在本文中,您將學習如何查詢給定字串中可以形成的子字串(非空)數量的方法。

Input : string = “moon”
Output : 10
Explanation: Substrings are ‘m’, ‘o’, ‘o’, ‘n’, ‘mo’, ‘oo’, ‘on’, ‘moo’, ‘oon’ and ‘moon’.

Input : string = “yellow”
Output : 21

查詢解決方案的方法

假設字串的長度為 n,因此從上面的示例中,我們瞭解到,為了找到所有可能的子字串數量,我們需要新增長度為 n、(n-1)、(n-2)、(n-3)、(n-4)、......2、1 的子字串。

子字串的總數 = n + (n - 1) + (n - 2) + (n - 3) + (n - 4) + ……. + 2 + 1。

= n * (n + 1) / 2

因此,現在我們有了計算子字串數量的公式,其中 n 是給定字串的長度。

上述方法的 C++ 程式碼

以下是我們可以用作輸入來解決給定問題的 C++ 語法 -

示例

#include<bits/stdc++.h>
using namespace std;
int main () {
   string str = "yellow";
   // finding the length of string
   int n = str.length ();
   // calculating result from formula
   int number_of_strings = n * (n + 1) / 2;
   cout << "Number of substrings of a string : " << number_of_strings;
   return 0;
}

輸出

Number of substrings of a string: 21

程式碼解釋

這是從給定字串中查詢所有可能的子字串數量的樂觀且直接的方法。

首先,在此程式碼中,我們從 .length() 函式中找到給定字串的長度,並將該值放入我們上面推匯出的公式中,列印儲存在 result 變數中的輸出。

結論

在本文中,我們解釋了查詢字串中子字串數量的方法,我們首先推匯出查詢所有可能的子字串數量的公式,並根據字串的長度使用公式獲得結果。我們可以在其他語言(如 C、Java、Python 和其他語言)中編寫相同的程式。我們希望您覺得本文有所幫助。

更新於:2021 年 11 月 25 日

6K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.