본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 151. Reverse Words in a String

반응형

Reverse Words in a String

Difficulty: Medium


Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

 

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: s = "  hello world  "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

 

Constraints:

  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

 

Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?

 

class Solution:
    def reverseWords(self, s: str) -> str:
        s = s.split()
        s.reverse()
        return " ".join(s)

비교적 쉬운 문제였다. split()을 하게 되면 기본 상태가 공백을 모두 제거한 상태에서 공백을 기준으로 나누기 때문에 공백이 존재하면 그 기준으로 나누고, 공백이 여러번 존재하게 되면 모두 무시하게 된다. 이 상태에서 reverse 를 한 후 문자열 형태로 반환. 

이때 공백으로 표시하는데 마지막 부분에는 또 공백이 표시되지 않기 때문에 이렇게 해도 쉽게 문제는 해결된다. 

반응형