0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

day6 at Leetcode

0
Last updated at Posted at 2026-07-13

151. Reverse Words in a String

split()join() を使えば楽に解けそうと当たりをつけて書いてみたが、出力が None になった。

class Solution:
    def reverseWords(self, s: str) -> str:
        word = s.split()
        word[::-1]
        ''.join(word)
原因は3つ:

word[::-1] は逆順にした新しいリストを作るだけで代入しないと結果が捨てられる
''.join(word) だと単語同士がスペースなしでくっついてしまう' '.join が正解
return を書いていないので関数は最後まで実行されても自動的に None を返す
修正版がこちら:

class Solution:
    def reverseWords(self, s: str) -> str:
        word = s.split()
        word = word[::-1]
        return ' '.join(word)
split() は引数なしで呼ぶと連続する複数スペースや先頭末尾の余分なスペースも自動で無視してくれるのがポイント" hello world ".split()  ['hello', 'world'] になるので今回のケース"a good example" みたいな複数スペースでも特別な処理をせずに対応できた
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?