如何在字符串之间交换元音

问题描述 投票:0回答:1

我有绳子

hello
元音必须交换,输出为
holle
e
o
被交换

下面是我的代码

vowels = ['a','e','i','o','u']

first_str = 'aiao'
l = list(first_str)
vowel_list = []
for vowel in l :
    if vowel in vowels:
        vowel_list.append(vowel)
for index,value in enumerate(l):
    if value in vowels:
#         print(value)
        l[index] = vowel_list[-1]
        vowel_list.remove(vowel_list[-1]) 
        print(vowel_list)
''.join(l)

我得到了输出

oaai
预期也是
oaia

我的方法

  1. 提取列表中的所有元音
  2. 遍历字符串
  3. 通过放置[-1]
  4. 从右侧迭代时交换元音
  5. 交换后从元音列表中删除元素

编辑礼貌@pranav 使用 pop 代码正在工作 ine

for index,value in enumerate(l):
    if value in vowels:
        l[index] = vowel_list.pop(-1)
''.join(l)
python string
1个回答
1
投票

给你

vowels = "aeiou"
str = 'aiao'
str = list(str)

i = 0 ; j = len(str)-1

while i < j:
    while i<j and str[i] not in v:
        i += 1
    while i<j and str[j] not in v:
        j -= 1
    str[i], str[j] = str[j], str[i]
    i += 1
    j -= 1

print("".join(str))
    

方法:(双指针方法)

  1. 设置两个指针(字符串的开始和结束)
  2. 移动指针直到找到元音
  3. 在指针处交换字符
  4. 重复此操作直到指针相互交叉

希望这个解决方案有帮助

© www.soinside.com 2019 - 2024. All rights reserved.