LeetCode #151: Reverse Words in a String
• 59 words • 1 min • updated
LeetCode #151: Reverse Words in a String:
python
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(s.split()[::-1])Note the following property of split():
python
>>> ' blue sky '.split()
['blue', 'sky']It strips leading and trailing whitespace. Furthermore, it collates multiple
whitespace characters in the middle. .split(' ') works as well. There’s no
need to call s.strip().