ZhongKuo0228 / study

0 stars 0 forks source link

345. Reverse Vowels of a String #63

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago

將出現過的母音字母翻轉順序

  1. 雙指針,往內掃描母音 pair
  2. 左右指針都掃到就調換
  3. left < right 即終止條件
class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = ['a', 'e', 'i', 'o', 'u']
        vowels.extend([w.upper() for w in vowels])
        words = list(s)
        left, right = 0, len(s) - 1
        while left < right:
            while words[left] not in vowels and left < right:
                left += 1
            while words[right] not in vowels and left < right:
                right -= 1
            words[left], words[right] = words[right], words[left]
            left, right = left + 1, right - 1
        return ''.join(words)
fockspaces commented 11 months ago

GPT improve

  1. 用 set + 字串 省去 hardcoded list (其實差不多,但可以打比較少字)
  2. 命名 words -> s_list 更具意義
class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = set("aeiouAEIOU")
        s_list = list(s)
        left, right = 0, len(s) - 1
        while left < right:
            while s_list[left] not in vowels and left < right:
                left += 1
            while s_list[right] not in vowels and left < right:
                right -= 1
            s_list[left], s_list[right] = s_list[right], s_list[left]
            left, right = left + 1, right - 1
        return ''.join(s_list)