用 C++ 列印以母音開始、以子音結尾的字串的所有子序列


本問題中,給定一個字串,要求找出給定字串的子串。要找的子串應以母音開頭,子音結尾。

字串是字元陣列。

本問題中要生成的目標字串可以透過刪除字串的某些字元來生成。且不改變字串的順序。

Input: ‘abc’
Output: ab, ac, abc

要解決這個問題,我們將迭代字串並固定母音並檢查下一個序列。我們來看一個演算法來找到一個解決方案 -

演算法

Step 1: Iterate of each character of the string, with variable i.
Step 2: If the ith character is a vowel.
Step 3: If the jth character is a consonant.
Step 4: Add to the HashSet, substring from 1st character to jth character.
Step 5: Repeat the following steps and find substrings from the string.

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
set<string> st;
bool isaVowel(char c);
bool isaConsonant(char c);
void findSubSequence(string str);
int main(){
   string s = "abekns";
   findSubSequence(s);
   cout<<"The substring generated are :\n";
   for (auto i : st)
      cout<<i<<" ";
   cout << endl;
   return 0;
}
bool isaVowel(char c) {
   return (c=='a'||c=='e'||c=='i'||c=='o'||c=='u');
}
bool isaConsonant(char c) {
   return !isaVowel(c);
}
void findSubSequence(string str) {
   for (int i = 0; i < str.length(); i++) {
      if (isaVowel(str[i])) {
         for (int j = str.length() - 1; j >= i; j--) {
            if (isaConsonant(str[j])) {
               string str_sub = str.substr(i, j + 1);
               st.insert(str_sub);
               for (int k = 1; k < str_sub.length() - 1; k++){
                  string sb = str_sub;
                  sb.erase(sb.begin() + k);
                  findSubSequence(sb);
               }
            }
         }
      }
   }
}

輸出

生成的目標字串有 -

ab abek abekn abekns abeks aben abens abes abk abkn abkns abks abn abns abs aek aekn aekns aeks aen aens aes ak akn akns aks an ans as ek ekn ekns eks en ens es

更新日期: 17-Jan-2020

459 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.