给定一个仅由元音组成的字符串,请在给定字符串找到最长的子序列,以使其由所有五个元音组成,并且是一个或多个a,一个或多个e,一个或多个i,然后是一个i,一个或多个o,然后是一个或多个u。
如果有一个以上的最长子序列,请打印任何一个。
例子:
Input : str = "aeiaaioooaauuaeiou"
Output : {a, a, a, a, a, a, e, i, o, u}
There are two possible outputs in this case:
{a, a, a, a, a, a, e, i, o, u} and,
{a, e, i, i, o, o, o, u, u, u}
each of length 10
Input : str = "aaauuiieeou"
Output : No subsequence possible
方法:
我们以递归方式遍历字符串中的所有字符,并遵循给定条件:
- 如果子序列为空,则仅当元音为“ a”时,才将其包含在当前索引中。否则,我们继续下一个索引。
- 如果当前索引处的元音与子序列中包含的最后一个元音相同,则将其包括在内。
- 如果当前索引处的元音是子序列中包含的最后一个元音之后的下一个可能的元音(即a–> e–> i–> o–> u),我们有两个选择:要么包含它,要么继续下一个索引。因此,我们选择给出最长子序列的序列。
- 如果以上条件都不满足,我们继续下一个索引(以避免在子序列中元音的无效排序)。
- 如果已经到达字符串的末尾,则检查当前子序列是否有效。如果它是有效的(即,如果它包含所有元音),则返回它,否则返回一个空列表。
方法1
下面是上述方法的实现:
C++
// C++ program to find the longest subsequence
// of vowels in the specified order
#include
using namespace std;
vector vowels = { 'a', 'e', 'i', 'o', 'u' };
// Mapping values for vowels
map mapping = { { 'a', 0 }, { 'e', 1 },
{ 'i', 2 }, { 'o', 3 },
{ 'u', 4 } };
// Function to check if given subsequence
// contains all the vowels or not
bool isValidSequence(string subList)
{
for(char c : vowels)
{
// not contain vovel
if (subList.find(c) == std::string::npos)
return 0;
}
return 1;
}
// Function to find the longest subsequence
// of vowels in the given string in specified
// order
string longestSubsequence(string str,
string subList,
int index)
{
// If we have reached the end of the
// string, return the subsequence
// if it is valid, else return an
// empty list
int len = str.length();
if (index >= len)
{
if (isValidSequence(subList))
return subList;
else
return "";
}
// If there is no vowel in the
// subsequence yet, add vowel
// at current index if it is 'a',
// else move on to the next character
// in the string
else if (subList.size() == 0)
{
if (str[index] != 'a')
return longestSubsequence(
str, "", index + 1);
else
return longestSubsequence(
str, subList + str[index],
index + 1);
}
// If the last vowel in the subsequence
// until now is same as the vowel at
// current index, add it to the subsequence
else if (mapping[subList[subList.size() - 1]] ==
mapping[str[index]])
return longestSubsequence(
str, subList+str[index], index + 1);
// If the vowel at the current index comes
// right after the last vowel in the
// subsequence, we have two options:
// either to add the vowel in the
// subsequence, or move on to next character.
// We choose the one which gives the longest
// subsequence.
else if (mapping[subList[subList.size() - 1]] + 1 ==
mapping[str[index]])
{
string sub1 = longestSubsequence(
str, subList + str[index], index + 1);
string sub2 = longestSubsequence(
str, subList, index + 1);
if (sub1.length() > sub2.length())
return sub1;
else
return sub2;
}
else
return longestSubsequence(
str, subList, index + 1);
}
// Driver Code
int main()
{
string str= "aeiaaioooauuaeiou";
string subsequence = longestSubsequence(
str, "", 0);
if (subsequence.length() == 0)
cout << "No subsequence possible\n";
else
cout << subsequence << "\n";
}
// This code is contributed by ajaykr00kj
Python3
# Python3 program to find the longest subsequence
# of vowels in the specified order
vowels = ['a', 'e', 'i', 'o', 'u']
# Mapping values for vowels
mapping = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
# Function to check if given subsequence
# contains all the vowels or not
def isValidSequence(subList):
for vowel in vowels:
if vowel not in subList:
return False
return True
# Function to find the longest subsequence of vowels
# in the given string in specified order
def longestSubsequence(string, subList, index):
# If we have reached the end of the string,
# return the subsequence
# if it is valid, else return an empty list
if index == len(string):
if isValidSequence(subList) == True:
return subList
else:
return []
else:
# If there is no vowel in the subsequence yet,
# add vowel at current index if it is 'a',
# else move on to the next character
# in the string
if len(subList) == 0:
if string[index] != 'a':
return longestSubsequence(string, subList, index + 1)
else:
return longestSubsequence(string, subList + \
[string[index]], index + 1)
# If the last vowel in the subsequence until
# now is same as the vowel at current index,
# add it to the subsequence
elif mapping[subList[-1]] == mapping[string[index]]:
return longestSubsequence(string, subList + \
[string[index]], index + 1)
# If the vowel at the current index comes
# right after the last vowel
# in the subsequence, we have two options:
# either to add the vowel in
# the subsequence, or move on to next character.
# We choose the one which gives the longest subsequence.
elif (mapping[subList[-1]] + 1) == mapping[string[index]]:
sub1 = longestSubsequence(string, subList + \
[string[index]], index + 1)
sub2 = longestSubsequence(string, subList, index + 1)
if len(sub1) > len(sub2):
return sub1
else:
return sub2
else:
return longestSubsequence(string, subList, index + 1)
# Driver Code
if __name__ == "__main__":
string = "aeiaaioooauuaeiou"
subsequence = longestSubsequence(string, [], 0)
if len(subsequence) == 0:
print("No subsequence possible")
else:
print(subsequence)
Python3
from random import choice
def longest_subsequence(string):
def helper(chosen="", i=0):
if i == len(string):
return chosen if set("aeiou").issubset(set(chosen)) else ""
hashable = (chosen[-1] if chosen else None, len(chosen), i)
if hashable in memo:
return memo[hashable]
if not chosen:
res = helper("a" if string[i] == "a" else chosen, i + 1)
elif chosen[-1] == string[i]:
res = helper(chosen + string[i], i + 1)
elif mapping[chosen[-1]] + 1 == mapping[string[i]]:
sub1 = helper(chosen + string[i], i + 1)
sub2 = helper(chosen, i + 1)
res = sub1 if len(sub1) > len(sub2) else sub2
else:
res = helper(chosen, i + 1)
memo[hashable] = res
return res
mapping = {x: i for i, x in enumerate("aeiou")}
memo = {}
return helper()
if __name__ == "__main__":
tests = [
"aeiaaioooaauuaeiou",
"aaauuiieeou",
"".join(choice("aeiou") for _ in range(40)),
"".join(choice("aeiou") for _ in range(900))
]
for string in tests:
print("original:", string)
subsequence = longest_subsequence(string)
if subsequence:
print("\nmax subsequence:", "".join(subsequence))
else:
print("No subsequence possible")
print("-" * 40, "\n")
输出:
['a', 'e', 'i', 'i', 'o', 'o', 'o', 'u', 'u', 'u']
方法2(动态编程)
Python3
from random import choice
def longest_subsequence(string):
def helper(chosen="", i=0):
if i == len(string):
return chosen if set("aeiou").issubset(set(chosen)) else ""
hashable = (chosen[-1] if chosen else None, len(chosen), i)
if hashable in memo:
return memo[hashable]
if not chosen:
res = helper("a" if string[i] == "a" else chosen, i + 1)
elif chosen[-1] == string[i]:
res = helper(chosen + string[i], i + 1)
elif mapping[chosen[-1]] + 1 == mapping[string[i]]:
sub1 = helper(chosen + string[i], i + 1)
sub2 = helper(chosen, i + 1)
res = sub1 if len(sub1) > len(sub2) else sub2
else:
res = helper(chosen, i + 1)
memo[hashable] = res
return res
mapping = {x: i for i, x in enumerate("aeiou")}
memo = {}
return helper()
if __name__ == "__main__":
tests = [
"aeiaaioooaauuaeiou",
"aaauuiieeou",
"".join(choice("aeiou") for _ in range(40)),
"".join(choice("aeiou") for _ in range(900))
]
for string in tests:
print("original:", string)
subsequence = longest_subsequence(string)
if subsequence:
print("\nmax subsequence:", "".join(subsequence))
else:
print("No subsequence possible")
print("-" * 40, "\n")
输出:
original: aeiaaioooaauuaeiou
max subsequence: aaaaaaeiou
----------------------------------------
original: aaauuiieeou
No subsequence possible
----------------------------------------
original: auaaioeoiaooaauoeuaueouuoeiiooiiaiiuioio
max subsequence: aaaaaaeeeiioou
----------------------------------------
original: eaaioeaieoaiueiuiaeiuueeueouoiuueeuaooooiuaiaeuaaieiauaiauuieaoeeeieeoiuaiuuuaaoieooooeioeiouuaoeaouooiauiuiioaoeeeuaoeooiueoaiuioeaeaaouiiiauiuuauoiaiaauaeooeuaiuoeeaaeoaiaoiueieeuaioieouuaaiieeaaeiioaoieoauieoueoauaieueoaeiaoaeoeuiaiauuauouoouaeaueeeioauaieiaieoaeiiueuaaoeuoiueaaiaiaouoouueoauoeieaioeeuueiaaoaiaiiaiueuauaeaieuioooiaeooeaueeoueiueeaueuuiaeuoiuiaeioeeuoaiuueuiaaueueuaeoueuaiaiiuiaouoiueuuueeaueeoaiaaouuiioeioeiaaiieaieiiieeeiaaoaeoououaooiioieuoaeaueuoeaueaoaieeeeauouaaaeiiuoiiuieuuoouuaaoiuaiaoaeeeeiauuuuoiuuoeiieuoaeaouaaooiuuuaeaeaeioeuuauaeaioiuuueuuiuieoieooeoiuioeouuuuaooeueaiooaeiieeieuauoeoaieaeiaaeeoiieiaeuouuuuououiuaueoeooaaeeuuiiaiiueoueaaauaiaieiuiiieauaaioauiuoiiiaieeuaieieiuooeaeooooeouioaooieooeaaaeeeuouiiooiaiieeeuoieeuueouiuuoioeeoiuaauuaaeaueeeiuuuueeeaaeuuoeeeuuieeueeuiaeioeaoiiiiauuoeieeioooaoaeueouiaoeouioaueoaioiuoieuoueuiuouiuaiiaeiuueaiaeuaaeouoa
max subsequence: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeiiiiiiiiiiiiiiiiiiiooooooooooooooouuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
----------------------------------------