2023年6月28日 星期三

6/28(每日一題)字串中母音的部分反轉

 Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

 

Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"

 

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consist of printable ASCII characters.

class Solution:
    def reverseVowels(self, s: str) -> str:
        #注意 str是不可變的,所以先製作一個list方便後面更動
        lis_s=list(s)
        vowels={'a','e','i','o','u','A','E','I','O','U'}
        lis_index=[]
        for n, i in enumerate(s):
            if i in vowels:
                lis_index.append(n)
        for i in range(len(lis_index)//2):
            lis_s[lis_index[i]], lis_s[lis_index[-1-i]]=lis_s[lis_index[-1-i]], lis_s[lis_index[i]]
#注意這邊用到的概念是因為運算是由右至左,
#所以記憶體會先記錄右邊賦值的資料,然後讀取左邊的運算要賦值到哪個索引
        return ''.join(lis_s)













標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁