在 Python 中查找包含所有元音的子字符串

pythonserver side programmingprogramming更新于 2025/9/27 6:36:17

假设我们有一个小写字母的字符串,我们必须找到至少包含一次所有元音且该子字符串中不存在辅音的子字符串。

因此,如果输入为"helloworldaeiouaieuonicestring",则输出将是 ['aeiou', 'aeioua', 'aeiouai', 'aeiouaiu', 'eioua', 'eiouai', 'eiouaiu']

为了解决这个问题,我们将遵循以下步骤 −

  • n := size of s

  • 对于范围从 0 到 n 的 i,执行

    • my_map := a new map

    • 对于范围从 i 到 n 的 j,执行

      • 如果 s[j] 不是元音,则

        • 退出循环

      • my_map[s[j]] := 1

      • 如果 my_map 的大小与 5 相同,则

        • 显示 s[从索引 i 到 j + 1]

示例

让我们看看下面的实现以便更好地理解 −

def isVowel(x):
   if x in ['a','e','i','o','u']:
      return True
   return False
def get_substrings(s):
   n = len(s)
   for i in range(n):
      my_map = dict()
      for j in range(i, n):
         if (isVowel(s[j]) == False):
            break
         my_map[s[j]] = 1
         if (len(my_map) == 5):
            print(s[i:j + 1])
s = "helloworldaeiouaiunicestring"
get_substrings(s)

输入

"helloworldaeiouaiunicestring"

输出

aeiou
aeioua
aeiouai
aeiouaiu
eioua
eiouai
eiouaiu

相关文章


有用资源