LeetCode/LeetCode75

[LeetCode 75] Medium - 151. Reverse Words in a String

hyunkookim 2024. 11. 11. 17:38

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. 단어의 순서를 뒤집습니다.
    • 입력 문자열의 단어들이 역순으로 배치됩니다.
  2. 여분의 공백 제거
    • 문자열 양쪽에 있는 앞뒤 공백과 단어 사이의 중복 공백은 제거합니다.
  3. 단어들은 단일 공백으로 구분됩니다.
    • 역순으로 배치된 단어들은 한 개의 공백(' ')으로만 구분됩니다.

 

class Solution:
    def reverseWords(self, s: str) -> str:
        # 1. 문자열을 분리하고 불필요한 공백 제거
        words = s.strip().split()
        # 2. 단어 리스트를 뒤집음
        reversed_words = words[::-1]
        # 3. 단일 공백으로 단어들을 연결
        return " ".join(reversed_words)

 

https://youtu.be/9lEkqOezpWw?si=5bCQFH8gG7-DPtD5

 

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