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

พิมพ์ลำดับของสตริงทั้งหมดที่ขึ้นต้นด้วยสระและลงท้ายด้วยพยัญชนะใน 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