Leetcode 151: Reverse Words in a String

151. Reverse Words in a String 

  • Total Accepted: 121339
  • Total Submissions: 769606
  • Difficulty: Medium

Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue“,
return “blue is sky the“.

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

 

Code

import re

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        return ' '.join(re.split('\s+', s.strip())[::-1])

 

 

Idea

I do not see many advanced methods in discussion that seem better than mine. One interesting method is to reverse the whole string first. Then reverse each word (so that the order within the word becomes normal again). These actions can happen in place so no more space is required.

Leave a comment

Your email address will not be published. Required fields are marked *