Skip to content

151. Reverse Words in a String

https://leetcode.com/problems/reverse-words-in-a-string/

js
/**
 * @param {string} str
 * @returns {string}
 */
var reverseWords = function(str) {
  return str.trim().split(/\s+/).reverse().join(' ')
}
py
class Solution(object):

    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        return ' '.join(reversed(s.strip().split()))