소프트웨어에 대한 모든 것

151. Reverse Words in a String 본문

알고리즘/LeetCode

151. Reverse Words in a String

앤테바 2022. 12. 17. 13:40
반응형

문제)

151. Reverse Words in a String

 

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?

 

 

솔루션1)

class Solution:
    def reverseWords(self, s: str) -> str:
        """
        - 문자열 s가 주어짐. 단어순으로 정렬
        - 단어는 스페이스가 없는 문자. s안에 있는 단어는 최소한 1개의 스페이스로 구분
        - 한 개의 스페이스로 구분된 reverse order로 단어를 나열해서 리턴        
        """
        words = s.split()
        words.reverse()
        return ' '.join(words)

 

반응형
Comments