Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 11. 12. 23:45

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

 

Reverse Words in a String - 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

그닥 어려운 문제는 아니었으나, 공백 처리하는 부분 삽질하느라 시간이 좀 걸림 =_=;

class Solution:
    def reverseWords(self, s: str) -> str:
        st = []        
        temp = ''
        for ss in s.strip():
            if ss == ' ' and temp == '':                
                continue
            if ss == ' ' and temp != '':
                st.append(temp)
                temp = ''                
                continue
            temp += ss
        if temp:
            st.append(temp)
        return ' '.join(st[::-1])
반응형