以括號形式列印以 C++ 中字串拆分的各種方式


在這個問題中,我們給定一個字串,我們必須將其分解成子字串,並在括號中列印它們。

讓我們舉幾個例子來更好地理解這個問題,

Input : wxyz
Output :
   (w) (x) (y) (z)
   (w) (x) (yz)
   (w) (xy) (z)
   (w) (xyz)
   (wx) (y) (z)
   (wx) (yz)
   (wxy) (z)
   (wxyz)

說明 − 我們將把字串分解為所有可能的子字串。並用括號括住每個子字串。

現在,由於我們已經理解了這個問題,讓我們建立一個解決該問題的方案吧。

在這裡,我們將使用遞迴來解決問題。我們將使用兩個引數,一個將是字串的下一個字元,另一個是輸出字串。未處理的子字串將在每次迭代時慢慢處理。子集也已建立。

示例

解決問題的程式 −

#include <iostream>
using namespace std;
void substring(string str, int index, string out){
   if (index == str.length())
      cout << out << endl;
   for (int i = index; i < str.length(); i++)
      substring(str, i + 1, out + "(" + str.substr(index, i+1-index) + ")" );
}
int main(){
   string str = "wxyz";
   cout<<”The substring are :”<<endl;
   substring(str, 0, "");
   return 0;
}

輸出

The substring are :
(w)(x)(y)(z)
(w)(x)(yz)
(w)(xy)(z)
(w)(xyz)
(wx)(y)(z)
(wx)(yz)
(wxy)(z)
(wxyz)

更新於:03 年 1 月 2020 日

123 瀏覽

開啟你的 職業道路

完成課程以取得認證

開始
廣告