0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

day5 at leetcode

0
Last updated at Posted at 2026-07-13

345. Reverse Vowels of a String

two pointer で左右から母音を探して交換する方式。

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = set('aeiouAEIOU')
        s = list(s)
        l, r = 0, len(s) - 1

        while l < r:
            if s[l] not in vowels:
                l += 1
            elif s[r] not in vowels:
                r -= 1
            else:
                s[l], s[r] = s[r], s[l]
                l += 1
                r -= 1

        return ''.join(s)

ポイントは3つ:

文字列は変更できないので list(s) で書き換え可能な形にして、最後に ''.join(s) で戻す
母音判定は list じゃなくて set を使うと in チェックがO(1)で速い
if / elif / else は1ループにつきどれか1つしか実行されない。ifがFalseなら同じループ内でelifをチェックしにいく(次のループまで待つわけじゃない)
最初は r -= 1 を r += 1 と書き間違えて、rがどんどん右に飛び出して IndexError になったのもいい学びだった。lは右へ、rは左へ動いて真ん中で出会うイメージを持つと間違えにくい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?