【问题标题】:How to swap the vowles between in the strings [closed]如何在字符串之间交换元音[关闭]
【发布时间】:2023-02-23 19:56:26
【问题描述】:

我有字符串

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

下面是我的代码

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. 交换后从元音列表中删除元素

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

    for index,value in enumerate(l):
        if value in vowels:
            l[index] = vowel_list.pop(-1)
    ''.join(l)
    

【问题讨论】:

  • 如果该列表具有重复元素,vowel_list.remove(vowel_list[-1]) 不会执行您期望的操作。也许你打算使用pop()
  • 另请指定该输入的预期输出背后的逻辑
  • @PranavHosangadi 为什么在删除索引时它不能处理重复元素。流行音乐也在工作
  • @abd remove() 方法删除第一次出现的指定元素。

标签: python string


【解决方案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 vowels:
        i += 1
    while i<j and str[j] not in vowels:
        j -= 1
    str[i], str[j] = str[j], str[i]
    i += 1
    j -= 1

print("".join(str))
    

方法:(双指针方法)

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

    希望这个解决方案有所帮助

【讨论】:

  • 不在 v: 中,这里的 v 是什么?元音
  • 是的。现在更新
猜你喜欢
  • 1970-01-01
  • 2012-02-28
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2016-06-29
  • 1970-01-01
  • 2016-01-30
相关资源
最近更新 更多