用 Python 反轉字串中的母音


假設我們有一個小寫字串。我們的任務是反轉字串中存在的母音。那麼,如果字串為“hello”,則反轉母音後的字串將為“holle”。對於字串“programming”,它將為“prigrammong”

為解決此問題,我們將執行以下步驟:

  • 獲取該字串並製作一個母音列表,並存儲它們的索引
  • 反轉母音列表
  • 設定 idx := 0
  • 針對 i 從 0 到給定字串的長度 - 1
    • 如果 i 在索引列表中 -
      • 將母音 [i] 放入最終字串
      • idx := idx + 1
    • 否則,將字串 [i] 放入最終字串
  • 以字串形式返回該列表

示例

讓我們看看以下實現來加深理解 -

 線上演示

class Solution:
   def reverseVowels(self, s):
      chars = list(s)
      index = []
      vowels = []
      for i in range(len(chars)):
         if chars[i] in ['a','e','i','o','u']:
         vowels.append(chars[i])
         index.append(i)
      vowels = vowels[::-1]
      final = []
      ind = 0
      for i in range(len(chars)):
      if i in index:
         final.append(vowels[ind])
         ind += 1
      else:
         final.append(chars[i])
   str1 = ""
   return str1.join(final)
ob1 = Solution()
print(ob1.reverseVowels("hello"))
print(ob1.reverseVowels("programming"))

輸入

"hello"
"programming"

輸出

holle
prigrammong

更新時間: 28-4-2020

4K+ 觀看次數

啟動你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.