본문 바로가기

자료구조,알고리즘

LeetCode-151 Reverse Words in a String 파이썬 풀

 

Reverse Words in a String - LeetCode

Can you solve this real interview question? 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 strin

leetcode.com

문제

문장을 단어단위로 뒤집는 문제입니다. 예를 들어 the sky is blue는 blue is sky the로 변경하여 반환하면 됩니다.

 

풀이

split을 사용해 공백을 기준으로 문자열을 나누어 줍니다. 저장된 배열을 거꾸로 뒤집고 뒤집어진 배열을 다시 문자열로 변경하면 됩니다.

class Solution:
    def reverseWords(self, s: str) -> str:
        result = ' '.join(s for s in reversed(s.split()))
        return result