Given a string str containing only alphabets, the task is to print the longest subsequence of the string str containing only vowels.
Examples:
Input: str = “geeksforgeeks”
Output: eeoee
Explanation:
“eeoee” is the longest subsequence of the string containing only vowels.
Input: str = “HelloWorld”
Output: eoo
Explanation:
“eeo” is the longest subsequence of the string containing only vowels.
Approach:
- Traverse through the given string character by character.
- If the character is a vowel, append it to the resultant string.
- When the traversal completes, the required longest subsequence containing only vowels is stored in the resultant string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isVowel( char x)
{
x = tolower (x);
return (x == 'a' || x == 'e'
|| x == 'i' || x == 'o'
|| x == 'u' );
}
string longestVowelSubsequence(string str)
{
string answer = "" ;
int n = str.size();
for ( int i = 0; i < n; i++) {
if (isVowel(str[i])) {
answer += str[i];
}
}
return answer;
}
int main()
{
string str = "geeksforgeeks" ;
cout << longestVowelSubsequence(str)
<< endl;
return 0;
}
|
Java
class GFG{
static boolean isVowel( char x)
{
x = Character.toLowerCase(x);
return (x == 'a' || x == 'e'
|| x == 'i' || x == 'o'
|| x == 'u' );
}
static String longestVowelSubsequence(String str)
{
String answer = "" ;
int n = str.length();
for ( int i = 0 ; i < n; i++) {
if (isVowel(str.charAt(i))) {
answer += str.charAt(i);
}
}
return answer;
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
System.out.print(longestVowelSubsequence(str)
+ "\n" );
}
}
|
Python 3
def isVowel(x):
return (x = = 'a' or x = = 'e' or x = = 'i' or x = = 'o' or x = = 'u' )
def longestVowelSubsequence( str ):
answer = ""
n = len ( str )
for i in range (n):
if (isVowel( str [i])):
answer + = str [i]
return answer
str = "geeksforgeeks"
print (longestVowelSubsequence( str ))
|
C#
using System;
class GFG{
static bool isVowel( char x)
{
x = char .ToLower(x);
return (x == 'a' || x == 'e'
|| x == 'i' || x == 'o'
|| x == 'u' );
}
static String longestVowelSubsequence(String str)
{
String answer = "" ;
int n = str.Length;
for ( int i = 0; i < n; i++) {
if (isVowel(str[i])) {
answer += str[i];
}
}
return answer;
}
public static void Main(String[] args)
{
String str = "geeksforgeeks" ;
Console.Write(longestVowelSubsequence(str)+ "\n" );
}
}
|
Javascript
<script>
function isVowel(x)
{
x = (x.toLowerCase());
return (x == 'a' || x == 'e'
|| x == 'i' || x == 'o'
|| x == 'u' );
}
function longestVowelSubsequence(str)
{
var answer = "" ;
var n = str.length;
for ( var i = 0; i < n; i++) {
if (isVowel(str[i])) {
answer += str[i];
}
}
return answer;
}
var str = "geeksforgeeks" ;
document.write( longestVowelSubsequence(str));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N), The extra space is used to store the result.