코딩 테스트/leetCode

[leetCode] 557. Reverse Words in a String III (Python)

우주바다 2022. 10. 30. 19:54
728x90

▼ 문제 바로가기 (링크) 

https://leetcode.com/problems/reverse-words-in-a-string-iii/

 

Reverse Words in a String III - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


문자열 s가 주어진다.

공백 기준으로 나눈 문자 단위로 순서를 뒤집고 

다시 공백 기준으로 합쳐서 문자열로 반환하는 문제.

 

class Solution:
    def reverseWords(self, s: str) -> str:
        a = s.split(' ')
        for i in range(len(a)):
            a[i] = a[i][::-1]
        a = " ".join(a)    
        return a

먼저 답을 담을 변수 a를 만들고,

split로 공백단위 자른 단어를 리스트 형태로 담았다.

 

반복문으로 리스트 a의 인덱스만큼을 순회하며

각 단어를 뒤집어서 재할당,

마지막으로 join 함수로 합쳐 저장했다.

728x90
반응형