用 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
广告