job 인터뷰/코테(Matroid) 준비

[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()))

 


내 코드

class Solution:
    def reverseWords(self, s: str) -> str:
        word = s.split(" ")
        # remove " "
        word = [w for w in word if w != '']
        # print(word)
        word = word[::-1]
        
        return " ".join(word)

 

솔루션

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

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

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.

설명:
단어는 무엇으로 구성되나요?
공백이 아닌 문자들의 조합이 단어를 구성합니다.
입력 문자열에 앞뒤 공백이 포함될 수 있나요?
네. 하지만 뒤집힌 문자열에는 앞뒤 공백이 포함되어서는 안 됩니다.
두 단어 사이에 공백이 여러 개 있는 경우는 어떨까요?
뒤집힌 문자열에서 공백을 하나의 공백으로 줄이세요.
"""


class Solution:
    def reverseWords(self, s):
        """
        Notice: ask how to deal with punctuations
        :param s: a string
        :return: a string
        """
        words_lst = s.split()  # not s.split(" ")
        words_lst = reversed(words_lst)
        return ' '.join(words_lst)

 

참고 사항

✅ s.split()

  • 공백(스페이스, 탭, 줄바꿈 등)을 모두 구분자로 사용
  • 여러 개의 연속된 공백도 하나처럼 처리
  • 양쪽 끝 공백도 자동 제거
s = "  hello   world\tpython  "
print(s.split())
# 출력: ['hello', 'world', 'python']

⚠️ s.split(" ")

  • 정확히 "스페이스 하나(" ")만을 기준으로 나눔
  • 연속된 공백은 빈 문자열("")로 유지
  • 탭(\t)이나 줄바꿈(\n)은 무시됨
s = "  hello   world\tpython  "
print(s.split(" "))
# 출력: ['', '', 'hello', '', '', 'world\tpython', '', '']

🔍 차이 요약표

구분 s.split() s.split(" ")
기준 문자 모든 공백 문자 (스페이스, 탭, 줄바꿈 등) 정확히 " " (스페이스 하나)
연속 공백 무시됨 (합쳐짐) 빈 문자열 포함
양끝 공백 무시(제거됨) 빈 문자열로 포함됨
예시 " a b \n c " → ['a','b','c'] " a b \n c " → ['', '', 'a', '', 'b', '\n', 'c']

🔚 결론

  • 일반적으로 단어를 나눌 때는 s.split() 사용이 더 안정적이에요.
  • 공백의 개수도 유지하고 싶다면 s.split(" ") 사용이 필요할 수 있어요.