관리 메뉴

솜씨좋은장씨

[leetCode] 151. Reverse Words in a String (Python) 본문

Programming/코딩 1일 1문제

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

솜씨좋은장씨 2020. 3. 3. 06:03
728x90
반응형

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

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: "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.

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up:

For C programmers, try to solve it in-place in O(1) extra space.

 

Solution

class Solution:
    def reverseWords(self, string) -> str:
        string.strip()

        split_strings = string.split()
        
        reversed_split_strings = list(reversed(split_strings))

        answer = ' '.join(reversed_split_strings)
        
        return answer

Solution 풀이

먼저 입력 받은 문자열에서 앞 뒤 공백을 strip( ) 함수를 통해 제거해줍니다.

그 후 split( ) 함수를 통해 공백을 기준으로 나눈 문자열들을 list로 만들어주고 

reversed( ) 함수를 통해 거꾸로 바꾸어준 후

' '.join( ) 함수를 통해 다시 문자열로 바꾸어 return 합니다.

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments